如何从多个DataFrame创建频次/值计数表并对比差异
问题描述
我有两个DataFrame,数据如下:
df1:
| country |
|---|
| US |
| US |
| CA |
| CN |
| AR |
df2:
| country |
|---|
| AR |
| AD |
| AO |
| AU |
| US |
需要将两个DataFrame的国家列表合并为集合后分组,对比两者间的差异,预期输出格式如下:
| country code | df1_country_count | df2_country_count |
|---|---|---|
| AR | 1 | 1 |
| AD | 0 | 1 |
| AO | 0 | 1 |
| AU | 0 | 1 |
| US | 2 | 1 |
| CA | 1 | 0 |
| CN | 1 | 0 |
解决方案
可以通过Pandas完成这个需求,步骤如下:
先分别统计两个DataFrame中每个国家的出现次数:
import pandas as pd # 构造示例数据 df1 = pd.DataFrame({'country': ['US', 'US', 'CA', 'CN', 'AR']}) df2 = pd.DataFrame({'country': ['AR', 'AD', 'AO', 'AU', 'US']}) # 统计df1的国家计数 df1_counts = df1.groupby('country').size().reset_index(name='df1_country_count') # 统计df2的国家计数 df2_counts = df2.groupby('country').size().reset_index(name='df2_country_count')对两个统计结果做全外连接,补全缺失的计数为0:
# 全外连接保留所有国家 merged = pd.merge(df1_counts, df2_counts, on='country', how='outer') # 把缺失的计数填充为0,并转为整数类型 merged = merged.fillna(0).astype({'df1_country_count': int, 'df2_country_count': int}) # 重命名列名匹配预期输出 merged = merged.rename(columns={'country': 'country code'})最终输出结果:
print(merged)
运行后就能得到和预期一致的表格。
内容的提问来源于stack exchange,提问作者Jiayu Zhang
相关产品推荐
相关产品推荐

