Skip to main content
 首页 » 编程设计

python之如何根据列值创建具有累计总和并具有分组依据的两列

2025年05月04日15kenshinobiy

我在使用 python3.7 的 pandas 中有以下数据框

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)  

出现以下错误 Series 的真值是不明确的。使用 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