如何按大洲分组并对% Renewable分箱后生成多级索引计数Series
问题:按大洲分组统计可再生能源占比分箱的国家数量
我需要按大洲分组,对每个国家的% Renewable浮点值进行分箱处理,最终生成以Continent和**% Renewable**为多级索引、计数为值的Series,要求每个大洲下包含所有分箱(即使该分箱内国家数量为0)。
现有进展
已完成全局分箱统计,代码如下:
groups = pd.value_counts(pd.cut(renew['% Renewable'], 5)) groups = pd.DataFrame(groups).reset_index()
得到的统计结果:
% Renewable counts 0 (2.213, 15.754] 7 1 (15.754, 29.228] 4 2 (29.228, 42.702] 2 3 (56.176, 69.65] 2 4 (42.702, 56.176] 0
期望输出
示例格式如下:
Asia (2.213, 15.754] 3 (15.754, 29.228] 1 (29.228, 42.702] 2 (56.176, 69.65] 0 (42.702, 56.176] 0 Europe (2.213, 15.754] 2 (15.754, 29.228] 2 (29.228, 42.702] 0 (56.176, 69.65] 1 (42.702, 56.176] 0 ....and so on
数据集片段
Country Continent % Renewable 0 China Asia (15.754, 29.228] 1 United States North America (2.213, 15.754] 2 Japan Asia (2.213, 15.754] 3 United Kingdom Europe (2.213, 15.754] 4 Russian Federation Europe (15.754, 29.228]
解决方案
步骤1:统一分箱规则
先计算全局分箱区间,确保所有大洲使用同一套分箱标准,避免分箱区间不一致:
# 获取全局分箱的所有区间 bins = pd.cut(renew['% Renewable'], 5).categories # 为原始数据添加分箱列 renew['renew_bin'] = pd.cut(renew['% Renewable'], bins=bins)
步骤2:分组计数并补全缺失分箱
按大洲和分箱分组统计后,通过重新索引补全所有分箱(包括计数为0的情况):
# 按大洲和分箱分组,统计每个组的国家数量 grouped_counts = renew.groupby(['Continent', 'renew_bin']).size() # 生成所有大洲与分箱的笛卡尔积索引,确保每个大洲包含所有分箱 full_multi_index = pd.MultiIndex.from_product( [renew['Continent'].unique(), bins], names=['Continent', '% Renewable'] ) # 重新索引,缺失的分箱计数填充为0 final_result = grouped_counts.reindex(full_multi_index, fill_value=0)
可选:转换为DataFrame
如果需要将结果转换为DataFrame格式,执行以下代码:
final_df = final_result.to_frame(name='counts')
内容的提问来源于stack exchange,提问作者Brian Cox
相关产品推荐
相关产品推荐

