Skip to main content
 首页 » 编程设计

python之来自两个 csv 文件的 Pandas Groupby

2024年12月31日10落叶无声

所以我正在做一个来自 Datacamp 的练习,告诉你从两个文件中按地区汇总预期生命周期。

life_fname with columns: ['Country', 'Life Expectancy']

来源:https://s3.amazonaws.com/assets.datacamp.com/production/course_1650/datasets/life_expectancy.csv

regions_fname with columns: ['Country', 'Region']

来源: https://s3.amazonaws.com/assets.datacamp.com/production/course_1650/datasets/regions.csv

# Read life_fname into a DataFrame: life 
life = pd.read_csv(life_fname, index_col='Country') 
 
# Read regions_fname into a DataFrame: regions 
regions = pd.read_csv(regions_fname, index_col='Country') 
 
# Group life by regions['region']: life_by_region 
life_by_region = life.groupby(regions['region']) 
 
print(life_by_region) 
# Print the mean over the '2010' column of life_by_region 
print(life_by_region['2010'].mean()) 

我了解 index_col 对一个数据帧的作用,但我不明白的是 python 如何知道在多个数据帧中找到“公分母”列 ['Country']?

我没有明确声明:

life['Country'] == regions['Country'].

请您参考如下方法:

您的猜测是正确的。 Pandas/Python 100% 不会推断出 life['Country'] == regions['Country']。如果我错了(我不是 Pandas 专家)有人纠正我,但是当你声明 life.groupby(regions['region']) 时,你是在告诉 pandas 做两件基本的事情:

首先:Pandas 发现您想要按regions['region'] 进行分组。为此,它将 regions['region'] 系列的所有索引映射到它们所属的任何组。

第二:Pandas 获取从索引到组的映射,并将它们应用于life Dataframe 的索引。

为什么会这样?纯属巧合。这样做的唯一原因是因为(a)你的数据帧长度相同,(b)你的数据帧索引恰好完美地重合。所以这个 groupby 操作碰巧成功了,但你应该知道这完全是偶然的。如果您想以一种明智且可靠的方式实际执行此操作,那么您应该合并 country (或任何合适的)上的两个 Dataframes,然后执行 groupby。希望这会有所帮助。

编辑:添加了有关如何正确执行此操作的示例:

pd.merge(life, regions, how='left', left_index=True,  
         right_index=True).groupby('region')['2010'].mean()