Python 熊猫:分组,过滤行,获取平均值

Python 熊猫:分组,过滤行,获取平均值,python,pandas,filter,group-by,mean,Python,Pandas,Filter,Group By,Mean,在python中,我有一个熊猫数据帧df,如下所示: ID Geo Speed 123 False 40 123 True 90 123 True 80 123 False 50 123 True 10 456 False 10 456 True 90 456 False 40 456 True 80 我想

在python中,我有一个熊猫数据帧
df
,如下所示:

 ID      Geo    Speed
123    False       40
123     True       90
123     True       80
123    False       50
123     True       10
456    False       10
456     True       90
456    False       40
456     True       80
我想按
ID
df
进行分组,过滤出
Geo==False
的行,并获得组中
速度的平均值。所以结果应该是这样的

 ID     Mean 
123       60  
456       85  
我的尝试:

df.groupby('ID')["Geo" == False].Speed.mean()
df.groupby('ID').filter(lambda g: g.Geo == False)
df[df.Geo.groupby(df.ID) == False]
他们两个都不工作。
有什么解决办法吗?谢谢大家!

使用
~
False
s转换为
True
s,通过
False
s进行过滤:

对于按
True
s进行过滤:

print (df[df["Geo"]])
    ID   Geo  Speed
1  123  True     90
2  123  True     80
4  123  True     10
6  456  True     90
8  456  True     80

df = df[df["Geo"]].groupby('ID', as_index=False).Speed.mean()
print (df)
    ID  Speed
0  123     60
1  456     85

使用
~
False
s转换为
True
s,通过
False
s进行过滤:

对于按
True
s进行过滤:

print (df[df["Geo"]])
    ID   Geo  Speed
1  123  True     90
2  123  True     80
4  123  True     10
6  456  True     90
8  456  True     80

df = df[df["Geo"]].groupby('ID', as_index=False).Speed.mean()
print (df)
    ID  Speed
0  123     60
1  456     85

通过使用
pivot\u表
,现在您可以得到正确和错误的平均值

df.pivot_table('Speed','ID','Geo',aggfunc='mean')
Out[154]: 
Geo  False  True 
ID               
123     45     60
456     25     85

通过使用
pivot\u表
,现在您可以得到正确和错误的平均值

df.pivot_table('Speed','ID','Geo',aggfunc='mean')
Out[154]: 
Geo  False  True 
ID               
123     45     60
456     25     85

df[df[“Geo”]==False].groupby('ID')['Speed'].mean()
df[df[“Geo”]==False].groupby('ID')['Speed'].mean()
谢谢您的回答@GabrielMacotti-如果可能,最好使用另一个值,如
True
False
s,如果布尔值更好,请使用
~
谢谢您的回答@GabrielMacotti-只有在可能的情况下,最好使用另一个值,如
True
False
s,如果布尔值更好,则使用
~