对数据框列中按一列分组并取决于其他列值的所有值求和

时间:2019-06-21 13:15:34

标签: python pandas dataframe conditional-statements apply

在特定月份中,我为每个人都有一个数字,用整数表示。我需要为每个人添加这些数字,直到每一行的指定日期为止。我想在python DataFrame上使用apply函数使其具有可伸缩性。

例如:

df = pd.DataFrame(
{'number': [10, 20 , 30, 40, 50], 'individual': ["John", "John" , "Eleonor", "Eleonor", "Eleonor"], 'date': [1, 2, 3, 4, 5]})

df =

   number individual  date
0      10       John     1
1      20       John     2
2      30    Eleonor     3
3      40    Eleonor     4
4      50    Eleonor     5

当日期严格低于行中的数字时,我想对数字求和,如果没有行具有满足条件的日期,则输入NA。 结果将是:

   number individual  date
0      NA       John     1
1      10       John     2
2      NA    Eleonor     3
3      30    Eleonor     4
4      70    Eleonor     5

2 个答案:

答案 0 :(得分:0)

df = pd.DataFrame({'num': [10, 20 , 30, 40, 50], 
                   'ind': ["John", "John" , "Eleonor", "Eleonor", "Eleonor"], 
                   'date': [1, 2, 3, 4, 5]})

df['x'] = df.groupby('ind')['num'].shift()
df['y'] = df.groupby('ind')['x'].cumsum()
print(df)

收益

   num      ind  date     x     y
0   10     John     1   NaN   NaN
1   20     John     2  10.0  10.0
2   30  Eleonor     3   NaN   NaN
3   40  Eleonor     4  30.0  30.0
4   50  Eleonor     5  40.0  70.0

答案 1 :(得分:0)

我找到了按要求使用apply方法的解决方案,该方法允许使用dask:

df['number'] = df.groupby("individual")['number'].apply(lambda x: x.expanding().sum().shift())

产生

   number individual  date
0     NaN       John     1
1    10.0       John     2
2     NaN    Eleonor     3
3    30.0    Eleonor     4
4    70.0    Eleonor     5
相关问题