Python - 计算 Pandas DataFrame 中的第一个组值
要计算第一个组值,请使用该方法。首先,使用别名导入所需的库-groupby.first()
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.first() 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.first() res = res.reset_index() print("\nFirst 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 First of group values = Car Place Units 0 BMW Delhi 100 1 Lexus Bangalore 150 2 Tesla Punjab 80