如何创建两个具有基于列值的累加总和并具有分组依据的列

时间:2019-09-07 20:01:54

标签: python python-3.x pandas

我正在使用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值具有累计数量qty

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()。

我也不知道它将在哪里给我预期的输出。你能帮我吗?

2 个答案:

答案 0 :(得分:4)

这是我的解决方法

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup 
container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home, container, false);

btnFertilizers = (Button)v.findViewById(R.id.btnFertilizers);

return v;


}

输出:

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()

答案 1 :(得分:2)

您可以使用:

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