分组后,根据其他列中的值之间的数据框范围求和一个单独的列 [英] Sum a seprate colum based on the range of the dataframe between values in other columns after groupby
本文介绍了分组后,根据其他列中的值之间的数据框范围求和一个单独的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下数据框
id Supply days days_180
1 30 0 180
1 100 183 363
1 80 250 430
2 5 0 180
2 5 10 190
3 5 0 180
3 30 100 280
3 30 150 330
3 30 200 380
3 30 280 460
3 50 310 490
我想对天数介于天数"与天数"之间的供应"求和.每行为天+ 180".需要对groupby('id')之后的每个组进行此操作.
I want to sum 'Supply' where days are between 'days' & 'days+180' for each row. This needs to be done for each group after groupby('id').
预期输出如下
id Supply days days_180 use
1 30 0 180 30
1 100 183 363 180
1 80 250 430 80
2 5 0 180 10
2 5 10 190 10
3 5 0 180 65
3 30 100 280 120
3 30 150 330 140
3 30 200 380 110
3 30 280 460 80
3 50 310 490 50
我已经尝试了下面的代码,但是无法正常工作.
I have tried the code below, but it is not working as intended.
df_d['use']=df_d.groupby('id').apply(lambda x: x.loc[x['days'].between(x['days'],x['days_180']),'supply'].sum())
推荐答案
使用列表推导对每个组中的每个days_180
值进行循环,使用sum
进行过滤并创建新列:
Use list comprehension for loop each days_180
values per groups, filter with sum
and create new column:
def f(x):
a = [x.loc[(x['days'] <= d) & (x['days_180'] >= d),'Supply'].sum() for d in x['days_180']]
x['use'] = a
return x
或使用另一个lambda解决方案:
Or solution with another lambda:
def f(x):
x['use'] = x['days_180'].apply(lambda d: x.loc[(x['days'] <= d) &
(x['days_180'] >= d), 'Supply'].sum())
return x
df_d = df_d.groupby('id').apply(f)
print (df_d)
id Supply days days_180 use
0 1 30 0 180 30
1 1 100 183 363 180
2 1 80 250 430 80
3 2 5 0 180 10
4 2 5 10 190 5
5 3 5 0 180 65
6 3 30 100 280 120
7 3 30 150 330 140
8 3 30 200 380 110
9 3 30 280 460 80
10 3 50 310 490 50
这篇关于分组后,根据其他列中的值之间的数据框范围求和一个单独的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文