首页 > 解决方案 > 来自两个 csv 文件的 Pandas Groupby

问题描述

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

life_fname 与列:['国家','预期寿命']

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

带有列的regions_fname:['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']?

我没有明确说明:

生活['国家'] == 地区['国家']。

标签: pythonpandaspandas-groupby

解决方案


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

第一:Pandas 看到你想要分组regions['region']。为了做到这一点,它将regions['region']系列的所有索引也映射到它们所属的任何组。

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

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

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

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

推荐阅读