gpt4 book ai didi

python - 比较数据框日期列并返回新列

转载 作者:行者123 更新时间:2023-11-30 22:05:54 25 4
gpt4 key购买 nike

我有一个数据框 df,由标识符列和 4 列日期组成。请参阅下面的数据框头部。

   Identifier                    A \
0 12253 1989-11-09 00:00:00
1 11413 1990-09-03 00:00:00
2 12337 1977-09-07 00:00:00
3 10610 1994-08-24 00:00:00
4 7493 1993-08-22 00:00:00

B C \
0 2012-03-01 00:00:00 2015-04-01 00:00:00
1 2009-08-16 00:00:00 2015-05-18 00:00:00
2 1977-09-07 00:00:00 1977-09-07 00:00:00
3 2009-01-09 00:00:00 2015-03-01 00:00:00
4 2002-06-03 00:00:00 2015-02-16 00:00:00

D \
0 2012-01-03 00:00:00
1 2015-05-18 00:00:00
2 1977-09-07 00:00:00
3 2015-03-01 00:00:00
4 2015-02-16 00:00:00

我试图将日期列相互比较,如果 A>=B>=C>=D 则在新列中检查应返回 True,否则返回 False。

因此生成的数据框将如下所示:

   Identifier                    A \
0 12253 1989-11-09 00:00:00
1 11413 1990-09-03 00:00:00
2 12337 1977-09-07 00:00:00
3 10610 1994-08-24 00:00:00
4 7493 1993-08-22 00:00:00

B C \
0 2012-03-01 00:00:00 2015-04-01 00:00:00
1 2009-08-16 00:00:00 2015-05-18 00:00:00
2 1977-09-07 00:00:00 1977-09-07 00:00:00
3 2009-01-09 00:00:00 2015-03-01 00:00:00
4 2002-06-03 00:00:00 2015-02-16 00:00:00

D Check\
0 2012-01-03 00:00:00 False
1 2015-05-18 00:00:00 True
2 1977-09-07 00:00:00 True
3 2015-03-01 00:00:00 True
4 2015-02-16 00:00:00 True

我已经尝试过

df['Check'] = np.where(df['A'] >= df['B']>= df['C']>= df['D'], 'True', 'False')

但无法让它发挥作用。接下来我可以尝试什么?

最佳答案

使用DataFrame.eval :

df['Check'] = df.eval('A <= B <= C <= D')
print (df)
Identifier A B C D Check
0 12253 1989-11-09 2012-03-01 2015-04-01 2012-01-03 False
1 11413 1990-09-03 2009-08-16 2015-05-18 2015-05-18 True
2 12337 1977-09-07 1977-09-07 1977-09-07 1977-09-07 True
3 10610 1994-08-24 2009-01-09 2015-03-01 2015-03-01 True
4 7493 1993-08-22 2002-06-03 2015-02-16 2015-02-16 True

关于python - 比较数据框日期列并返回新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52871358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com