如何在每组 Pandas DataFrame 上应用聚合列表?
要应用聚合列表,请使用agg()方法。首先,导入所需的库-
import pandas as pd
创建一个包含两列的DataFrame-
dataFrame = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Lexus', 'Mustang', 'Bentley', 'Mustang'],"Units": [100, 150, 110, 80, 110, 90] } )
指定列表作为参数使用agg()-
dataFrame = dataFrame.groupby('Car').agg(list)
示例
以下是完整的代码-
import pandas as pd # Create DataFrame dataFrame = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Lexus', 'Mustang', 'Bentley', 'Mustang'],"Units": [100, 150, 110, 80, 110, 90] } ) print("DataFrame ...\n",dataFrame) # specifying list as argument using agg() dataFrame = dataFrame.groupby('Car').agg(list) # displaying dataframe lists print("\nDataFrame ...\n",dataFrame)输出结果
这将产生以下输出-
DataFrame ... Car Units 0 BMW 100 1 Lexus 150 2 Lexus 110 3 Mustang 80 4 Bentley 110 5 Mustang 90 DataFrame ... Units Car BMW [100] Bentley [110] Lexus [150,110] Mustang [80,90]