如何创建两列,其累积总和基于列值并具有分组依据



我在使用 python3.7 的熊猫中有以下数据帧

data = {'s':['a','a','a','a','b','b'],
'cp':['C','P','C','C','C','P'],
'st':[300,300,300,300,310,310],
'qty':[3000,3000,3000,6000,9000,3000],
'p':[16,15,14,10,8,12]}
df=pd.DataFrame(data)
df['t']=df['p']*df['qty']
df['ct']=df['t'].cumsum()
df
s   cp  st  qty p   t   ct
0   a   C   300 3000    16  48000   48000
1   a   P   300 3000    15  45000   93000
2   a   C   300 3000    14  42000   135000
3   a   C   300 6000    10  60000   195000
4   b   C   310 9000    8   72000   267000
5   b   P   310 3000    12  36000   303000

我想创建两个单独的列,例如基于 S 的 x 和 y,以及具有累积数量总和的 CP 值

col x = cumm qty where cp="c" group by col s
col y = cumm qty where cp=P group by col s
s   cp  st  qty p   t   ct                x      y
0   a   C   300 3000    16  48000   48000     3000     0
1   a   P   300 3000    15  45000   93000     3000   3000
2   a   C   300 3000    14  42000   135000    6000   3000
3   a   C   300 6000    10  60000   195000   12000   3000
4   b   C   310 9000    8   72000   267000    9000     0
5   b   P   310 3000    12  36000   303000    9000   3000
I tried something like this
df['x']=df.loc[df['p']>0].groupby(['s'])['s','cp','qty','ct'].apply(lambda x:x['qty'].cumsum() if x['cp']=="C" else 0) 

它给出以下错误 序列的真值是不明确的。使用 a.empty、a.bool((、a.item((、a.any(( 或 a.all((。

我也不确定它会在哪里给我预期的输出。你能帮我吗?

这是我的解决方案

df['x'] = df['qty'].mul(df['cp'].eq('C')).groupby(df['s']).cumsum()
df['y'] = df['qty'].mul(df['cp'].eq('P')).groupby(df['s']).cumsum()

输出:

s cp   st   qty   p      t      ct      x     y
0  a  C  300  3000  16  48000   48000   3000     0
1  a  P  300  3000  15  45000   93000   3000  3000
2  a  C  300  3000  14  42000  135000   6000  3000
3  a  C  300  6000  10  60000  195000  12000  3000
4  b  C  310  9000   8  72000  267000   9000     0
5  b  P  310  3000  12  36000  303000   9000  3000

您可以使用:

df['X']=df.where(df['cp'].eq('C')).groupby('s')['qty'].cumsum().fillna(df['qty'])
df['Y']=0
df.loc[~df['cp'].shift(-1).eq('P'),'Y']=df.loc[df['cp'].eq('P'),'qty']
df=df.ffill()

s   cp  st  qty p   t   ct                x      y
0   a   C   300 3000    16  48000   48000     3000     0
1   a   P   300 3000    15  45000   93000     3000   3000
2   a   C   300 3000    14  42000   135000    6000   3000
3   a   C   300 6000    10  60000   195000   12000   3000
4   b   C   310 9000    8   72000   267000    9000     0
5   b   P   310 3000    12  36000   303000    9000   3000

最新更新