gpt4 book ai didi

python - 按列分组并比较日期 : Pandas

转载 作者:行者123 更新时间:2023-12-05 02:36:24 25 4
gpt4 key购买 nike

我有以下数据框。

ID  Date1        Date2
1 7-12-2021 20-11-2021
1 10-11-2021 01-12-2021
2 22-10-2021 03-12-2021

我的想法是基于 ID 列的重复值比较两个日期,如果 Date2 早于 Date1,则保留该行。如果ID的值是唯一的,则无需比较,保持原值。

我想获得以下输出。

ID  Date1        Date2
1 10-11-2021 01-12-2021
2 22-10-2021 03-12-2021

我试过如下但没有成功。

df = df.groupby(['ID'])[(df['Date1']) < (df['Date2'])]

谁能帮我解决这个问题?

最佳答案

我首先要确保您的日期列是日期时间类型,然后检查 ID 列中的重复项以及 Date2 是否在 Date1 之前,如果是这种情况则删除:

# Convert to datetime
df['Date1'] = pd.to_datetime(df['Date1'])
df['Date2'] = pd.to_datetime(df['Date2'])

# Mark what you need to drop
df.loc[df.ID.duplicated(keep=False),'ind'] = 'dup'
df['ind'] = np.where((df.ind.eq('dup')) & (df['Date2'] > df['Date1']),'Drop','Keep')

>>> print(df.loc[df['ind'].eq('Keep')].drop('ind',axis=1))

ID Date1 Date2
1 1 2021-10-11 2021-01-12
2 2 2021-10-22 2021-03-12

关于python - 按列分组并比较日期 : Pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70264126/

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