获取组Python中与最小和最大日期相关联的值的差异

2024-04-26 17:57:10 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是数据帧:

ID     Date1         Date2  weight
123 1/1/2018    12/31/2018  147
123 1/1/2018    11/30/2018  136
123 1/1/2018    10/30/2018  128
123 1/1/2018    4/30/2000   150
123 5/5/2017    4/4/2017    160
123 5/5/2017    1/1/2016    170
524 4/4/2017    4/3/2017    180
524 4/4/2017    4/1/2017    150
524 4/4/2017    3/31/2017   130
524 3/3/2017    2/2/2017    210
524 3/3/2017    1/1/2017    250
524 2/3/2017    1/3/2017    230

对于每个ID和Date1组,我需要与最小和最大Date2相关联的权重的差异。预期输出为:

ID  Date1   Weight_Diff
123 1/1/2018     -3
123 5/5/2017    -10
524 4/4/2017     50
524 3/3/2017    -40
524 2/3/2017      0

我试过以下方法,但没有效果:

maxdate = df.groupby(['ID','Date1'])['Date2'].idxmax()
mindate = df.groupby(['ID','Date1'])['Date2'].idxmin()

df['diff'] = df.iloc[maxdate]['weight'] - df.iloc[mindate]['weight']

Tags: 数据方法iddfdiff差异权重groupby
1条回答
网友
1楼 · 发布于 2024-04-26 17:57:10

我觉得我能想到的最可读的东西是:

g = df.groupby(['ID','Date1'])
diff = g.nth(0)['weight'] - g.nth(-1)['weight']
print(diff.reset_index())

假设:您已经对列date1和date2进行了排序

退货:

    ID     Date1  weight
0  123  1/1/2018      -3
1  123  5/5/2017     -10
2  524  2/3/2017       0
3  524  3/3/2017     -40
4  524  4/4/2017      50

相关问题 更多 >