Python - 如何在 Groupby 熊猫之后重置索引?
要在groupby后重置索引,首先根据列使用groupby().之后,使用reset_index().
首先,导入所需的库-
import pandas as pd
创建一个具有2列的DataFrame-
dataFrame = pd.DataFrame(
{
"Car": ["Audi", "Lexus", "Audi", "Mercedes", "Audi", "Lexus", "Mercedes", "Lexus", "Mercedes"],
"Reg_Price": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350]
}
)根据Car列分组-
resDF = dataFrame.groupby("Car").mean()现在,分组后重置索引-
resDF.reset_index()
示例
以下是代码-
import pandas as pd
#创建一个包含两列的数据框
dataFrame = pd.DataFrame(
{
"Car": ["Audi", "Lexus", "Audi", "Mercedes", "Audi", "Lexus", "Mercedes", "Lexus", "Mercedes"],
"Reg_Price": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350]
}
)
print"DataFrame...\n",dataFrame
#按汽车分组
resDF = dataFrame.groupby("Car").mean()
print"\nDataFrame...\n", resDF
#分组后重置索引
print"\nReset index after grouping...\n", resDF.reset_index()输出结果这将产生以下输出-
DataFrame...
Car Reg_Price
0 Audi 1000
1 Lexus 1400
2 Audi 1100
3 Mercedes 900
4 Audi 1700
5 Lexus 1800
6 Mercedes 1300
7 Lexus 1150
8 Mercedes 1350
DataFrame...
Reg_Price
Car
Audi 1266.666667
Lexus 1450.000000
Mercedes 1183.333333
Reset index after grouping...
Car Reg_Price
0 Audi 1266.666667
1 Lexus 1450.000000
2 Mercedes 1183.333333