Python——在 Pandas 的 Groupby 之后如何重置索引?
要在按组操作后重置索引,首先应该使用 groupby() 根据某列进行分组。然后,使用 reset_index()。
首先,导入所需的库——
import pandas as pd
创建一个有 2 列的数据框——
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 # creating a dataframe with two columns 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 # grouped according to Car resDF = dataFrame.groupby("Car").mean() print"\nDataFrame...\n", resDF # resetting index after grouping 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
广告