要计算组值的最后一个,请使用该方法。首先,使用别名导入所需的库 -groupby.last()
import pandas as pd;
创建一个包含 3 列的 DataFrame -
dataFrame = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'BMW', 'Tesla', 'Lexus', 'Tesla'],"Place": ['Delhi','Bangalore','Pune','Punjab','Chandigarh','Mumbai'],"Units": [100, 150, 50, 80, 110, 90] } )
现在,按列对 DataFrame 进行分组 -
groupDF = dataFrame.groupby("Car")
计算组值的最后一个并重置索引 -
res = groupDF.last() res = res.reset_index()
以下是完整代码。显示最后一次出现的重复值,即组值的最后一次 -
import pandas as pd; dataFrame = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'BMW', 'Tesla', 'Lexus', 'Tesla'],"Place": ['Delhi','Bangalore','Pune','Punjab','Chandigarh','Mumbai'],"Units": [100, 150, 50, 80, 110, 90] } ) print"DataFrame ...\n",dataFrame # 按列 Car 对 DataFrame 进行分组 groupDF = dataFrame.groupby("Car") res = groupDF.last() res = res.reset_index() print"\nLast of group values = \n",res输出结果
这将产生以下输出 -
DataFrame ... Car Place Units 0 BMW Delhi 100 1 Lexus Bangalore 150 2 BMW Pune 50 3 Tesla Punjab 80 4 Lexus Chandigarh 110 5 Tesla Mumbai 90 Last of group values = Car Place Units 0 BMW Pune 50 1 Lexus Chandigarh 110 2 Tesla Mumbai 90