筛选多级分组依据

2024-04-27 03:43:24 发布

您现在位置:Python中文网/ 问答频道 /正文

如何按多级过滤组?你知道吗

示例:

import pandas as pd

df = pd.DataFrame( {"Country" : ["Brazil", "Brazil", "Brazil", "Italy", "Italy", "Brazil"],
                    "City" : ["Sao Paulo", "Sao Paulo", "Rio de Janeiro", "Roma", "Roma", "Sao Paulo"],
                    "Vehicule" : ["Bike", "Car", "Car", "Car", "Bike", "Bike"],
                    "Value" : [1, 2, 3, 4, 5,6]})
group = df.groupby(by=["Country", "City", "Vehicule"]).sum().loc[:,"Value"]
print(group)

我怎样才能只过滤级别的车辆“自行车”,并显示我的自行车和汽车的百分比。你知道吗


Tags: citydfvaluegroup自行车carcountrypd
1条回答
网友
1楼 · 发布于 2024-04-27 03:43:24

一种简单的方法是先过滤,然后分组:

df[df.Vehicule=="Bike"].groupby(["Country", "City"]).sum()

或:

df.groupby(["Country", "City", "Vehicule"]).sum().unstack().Value.Bike

后者为没有的城市生成NaN:

Country  City          
Brazil   Rio de Janeiro    NaN
         Sao Paulo         7.0
Italy    Roma              5.0

或作为分数:

x = df.groupby(["Country", "City", "Vehicule"]).sum().unstack().Value
x.Bike / x.sum(1)

给你:

Country  City          
Brazil   Rio de Janeiro         NaN
         Sao Paulo         0.777778
Italy    Roma              0.555556

相关问题 更多 >