Groupby和熊猫数据框上的条件

时间:2018-08-02 01:59:56

标签: python-3.x pandas dataframe

我有一个下面的数据框

      df=
         city    code     qty1   qty2  month    type
         hyd     1        10     12       1      x 
         hyd     2        12     21              y
         hyd     2        15     36              x 
         hyd     4        25     44       3      z     
         pune    1        10     1               x
         pune    3        12     2        2      y
         pune    1        15     3               x   
         pune    2        25     4               x
         ban     2        10     1        1      X       
         ban     4        10     2               x  
         ban     2        12     3               x
         ban     1        15     4        3      y  

我想对(城市和代码)进行分组,并根据以下条件找到res1和res2。

结果数据帧为

result=  
     city    code     res1     res2  
     hyd     1        Nan       12      
     hyd     2        27        Nan
     hyd     4        Nan       Nan     
     pune    1        25        Nan
     pune    3        Nan       Nan
     pune    2        25        Nan
     ban     2        12        10  
     ban     4        10        Nan
     ban     1        Nan       Nan 

我尝试对条件进行分组和对groupyby的结果进行迭代。但是没有结果。任何帮助,将不胜感激。谢谢

2 个答案:

答案 0 :(得分:0)

您可以groupby一次计算出所需的内容,然后concat返回

g=df.groupby(['city','code'])
pd.concat([g.apply(lambda x : sum(x['qty1'][x['month']==''])),g.apply(lambda x : sum(x['qty2'][(x['month']!='')&(x['type']=='x')]))],axis=1)
Out[135]: 
            0   1
city code        
ban  1      0   0
     2     12   0
     4     10   0
hyd  1      0  12
     2     27   0
     4      0   0
pune 1     25   0
     2     25   0
     3      0   0

答案 1 :(得分:0)

IIUC

df = df.set_index(['city', 'code'])

cond1 = df.month.isnull()
df['res1'] = df[cond1].groupby(['city', 'code']).qty1.sum()

cond2 = df.month.notnull() & (df.type=='x')
df['res2'] = df[cond2].groupby(['city', 'code']).qty2.sum()


             qty1   qty2    month   type    res1    res2
city    code                        
hyd     1    10     12      1.0     x       NaN     12.0
        2    12     21      NaN     y       27.0    NaN
        2    15     36      NaN     x       27.0    NaN
        4    25     44      3.0     z       NaN     NaN
pune    1    10     1       NaN     x       25.0    NaN
        3    12     2       2.0     y       NaN     NaN
        1    15     3       NaN     x       25.0    NaN
        2    25     4       NaN     x       25.0    NaN
ban     2    10     1       1.0     x       12.0    1.0
        4    10     2       NaN     x       10.0    NaN
        2    12     3       NaN     x       12.0    1.0
        1    15     4       3.0     y       NaN     NaN