提问人:Django0602 提问时间:2/24/2023 更新时间:2/24/2023 访问量:85
Pandas 根据月和年比较值
Pandas comparing values based on month and year
问:
在我目前的问题陈述中,我想比较两个不同列中的值,这些列与特定月份对齐,并返回一个充当标识符的值。我的数据帧如下所示:
Account year month value_1 value_2
A 2021 Jan 9
A 2021 Feb
A 2021 Mar 7
A 2021 Apr 8
A 2021 May
B 2021 Jan 2
B 2021 Feb 10
B 2021 Mar 5
B 2021 Apr 7
现在,在上面的场景中,对于账户 A,与 value_1 相比,值 9 出现在value_2列中,值 2 出现在value_2列中的值 10 之前。从本质上讲value_2我想比较一下,如果每个帐户value_1列之前都出现在列值之前,并且这些列已经按月份和年份排序。
我想做的是创建一个结果数据帧,显示以下内容:
account result
A value_2 appeared before value_1
B value_1 appeared before value_2
我怎样才能做到这一点?
答:
1赞
Pedro Rocha
2/24/2023
#1
假设每组至少有 1 个值,并且同一行中永远不会有 2 个值......这应该对你有用。
def check_order(group):
value_1_idx = group['value_1'].dropna().index.min()
value_2_idx = group['value_2'].dropna().index.min()
if (value_1_idx.min() < value_2_idx) or ((value_2_idx is np.nan) & (value_1_idx != np.nan)):
return 'value_1 appeared before value_2'
elif (value_2_idx < value_1_idx) or ((value_1_idx is np.nan) & (value_2_idx != np.nan)):
return 'value_2 appeared before value_1'
result = df.groupby('Account').apply(check_order).reset_index(name='result')
评论