Expressing pandas subset using pipe

后端 未结 3 2232
滥情空心
滥情空心 2021-02-15 06:24

I have a dataframe that I subset like this:

   a  b   x  y
0  1  2   3 -1
1  2  4   6 -2
2  3  6   6 -3
3  4  8   3 -4

df = df[(df.a >= 2) & (df.b <=          


        
3条回答
  •  北荒
    北荒 (楼主)
    2021-02-15 06:38

    You can try, but I think it is more complicated:

    print df[(df.a >= 2) & (df.b <= 8)].groupby(df.x).mean()
         a  b  x    y
    x                
    3  4.0  8  3 -4.0
    6  2.5  5  6 -2.5
    
    
    def masker(df, mask):
        return df[mask]
    
    mask1 = (df.a >= 2)
    mask2 = (df.b <= 8)     
    
    print df.pipe(masker, mask1).pipe(masker, mask2).groupby(df.x).mean()
         a  b  x    y
    x                
    3  4.0  8  3 -4.0
    6  2.5  5  6 -2.5
    

提交回复
热议问题