【发布时间】:2019-06-18 02:37:59
【问题描述】:
我有以下 df,我想按 Date & Ref 对其进行分组,但要使用 sum 条件。
在这方面,只有当 P >= 比 PP 时,我才需要按 Date & Ref 和总和“Q”列进行分组。
df = DataFrame({'Date' : ['1', '1', '1', '1'],
'Ref' : ['one', 'one', 'two', 'two'],
'P' : ['50', '65', '30', '38'],
'PP' : ['63', '63', '32', '32'],
'Q' : ['10', '15', '20', '10']})
df.groupby(['Date','Ref'])['Q'].sum() #This does the right grouping byt summing the whole column
df.loc[df['P'] >= df['PP'], ('Q')].sum() #this has the right sum condition, but does not divide between Date & Ref
有没有办法做到这一点? 非常感谢提前
【问题讨论】:
标签: python python-3.x pandas group-by pandas-loc