Pandas groupby的平均值,在变量上截断后

Pandas groupby的平均值,在变量上截断后,pandas,dataframe,Pandas,Dataframe,我想要有一个列,它引用groupby中变量X的平均值,只使用在变量Y上通过剪切的行 我已经做了一点变通,所以我想知道是否有一个更艰难的方法来实现这一点 df = pd.DataFrame({'Animal': ['Falcon', 'Falcon', 'Falcon', 'Parrot', 'Parrot','Parrot'], 'Max_Speed': [380., 370., 90, 24., 100., 101]}) df['meanWithCut'

我想要有一个列,它引用groupby中变量X的平均值,只使用在变量Y上通过剪切的行

我已经做了一点变通,所以我想知道是否有一个更艰难的方法来实现这一点

df = pd.DataFrame({'Animal': ['Falcon', 'Falcon', 'Falcon', 'Parrot', 'Parrot','Parrot'],
                   'Max_Speed': [380., 370., 90, 24., 100., 101]})

df['meanWithCut'] = df.query('Max_Speed>98').groupby('Animal').transform('mean')

df['meanWithCut'] = df.groupby('Animal')['meanWithCut'].apply(lambda x: x.fillna(x.max()))

df

    Animal  Max_Speed   meanWithCut
0   Falcon  380.0       375.0
1   Falcon  370.0       375.0
2   Falcon  90.0        375.0
3   Parrot  24.0        100.5
4   Parrot  100.0       100.5
5   Parrot  101.0       100.5


如果在分配之前需要筛选,我将执行agg,然后映射回

s = df.query('Max_Speed>98').groupby('Animal').agg('mean')
df['meanWithCut'] = s.reindex(df.Animal).values
df
Out[130]: 
   Animal  Max_Speed  meanWithCut
0  Falcon      380.0        375.0
1  Falcon      370.0        375.0
2  Falcon       90.0        375.0
3  Parrot       24.0        100.5
4  Parrot      100.0        100.5
5  Parrot      101.0        100.5
一鼓作气

df['meanWithCut'] = df.query('Max_Speed>98').groupby('Animal').agg('mean').reindex(df.Animal).values

如果在分配之前需要筛选,我将执行agg,然后映射回

s = df.query('Max_Speed>98').groupby('Animal').agg('mean')
df['meanWithCut'] = s.reindex(df.Animal).values
df
Out[130]: 
   Animal  Max_Speed  meanWithCut
0  Falcon      380.0        375.0
1  Falcon      370.0        375.0
2  Falcon       90.0        375.0
3  Parrot       24.0        100.5
4  Parrot      100.0        100.5
5  Parrot      101.0        100.5
一鼓作气

df['meanWithCut'] = df.query('Max_Speed>98').groupby('Animal').agg('mean').reindex(df.Animal).values
你可以:

你可以: