假设我具有以下测试DataFrame df:
Car Sold make profit
Honda 100 Accord 10
Honda 20 Fit 5
Toyota 300 Corolla 20
Hyundai 150 Elantra 20
BMW 20 Z-class 100
Toyota 45 Lexus 7
BMW 50 X-class 30
JEEP 150 cherokee 2
Honda 20 CRV 5
Toyota 30 Yaris 3
我需要一个汇总统计表,用于按汽车类型划分的售出汽车数量。
我可以这样操作:
df.groupby('Car')['Sold'].describe()
这给了我类似以下内容:
Car count mean std min 25th 50th 75th max
BMW 2
Honda 3
Hyundai 1
JEEP 1
Toyota 3
[Car
]列值在摘要统计表中以字母升序列出。我正在寻找一种以我自己预先指定的方式对其进行排序的方法。我希望摘要统计表列为"Toyota, Hyundai, JEEP, BMW, Honda"
df.groupby('Car')['Sold'].describe().loc[["Toyota", "Hyundai", "JEEP", "BMW", "Honda"]]
帮助我将其整理好,但是我无法进行多级索引编制。例如,如果我要汇总统计表以“ Car
”表示,并且进一步以make表示,则.loc
不能为我提供所需的解决方案。