【问题标题】:Merging different sized data frames and plotting the difference of a column合并不同大小的数据框并绘制列的差异
【发布时间】:2021-10-04 08:45:06
【问题描述】:

我有两个数据框 Region_education_0 和 Region_education_1 Region_education_0

index Region ConvertedComp
1 Australia/New Zealand 122573.834171
2 Caribbean 53562.111111
3 Central Asia 134422.000000
4 East Asia 112492.507042
5 Melanesia 605

Region_education_1

index Region ConvertedComp
1 Australia/New Zealand 122573.834171
2 Caribbean 53562.111111
3 Central Asia 134422.000000
4 East Asia 112492.507042

索引 5,Region_education_1 中不存在美拉尼西亚,因为某种情况,我想比较它们并绘制,所以我尝试了这个

from matplotlib.pyplot import *

Region_education_combined=Region_education_0.merge(Region_education_1,left_on="Region",right_on="Region")
Region_education_combined.columns=["Region","Max of Bachelors Higher Ed","Higher Formal Education"]
Region_education_combined['Diff_HigherEd_Vals'] = Region_education_combined['Higher Formal Education'] - Region_education_combined['Max of Bachelors Higher Ed']
print(Region_education_combined)
comp_df.style.bar(subset=['Diff_HigherEd_Vals'], align='mid', color=['#d65f5f', '#5fba7d'])

index Max of Bachelors Higher Ed Higher Formal Education Diff_HigherEd_Vals
1 151698.500659 122573.834171 -29124.666488
2 28413.753425 53562.111111 53562.111111
3 3944.750000 5883.000000 1938.250000
4 45091.041667 27052.384615 -18038.657051

输出中缺少区域列,包括我尝试过的区域


comp_df.style.bar(subset=['Diff_HigherEd_Vals','Region'], align='mid', color=['#d65f5f', '#5fba7d'])


comp_df.style.bar(Region_education_combined, align='mid', color=['#d65f5f', '#5fba7d'])

有没有办法在最终输出中包含区域? 我从“Region_education_0”数据框中省略了“索引 5,美拉尼西亚”,有没有办法将它也包含在输出中?

【问题讨论】:

    标签: python pandas dataframe matplotlib


    【解决方案1】:

    当您像这样调用merge 时,您可以使用how="outer" 来维护丢失的区域

    Region_education_combined=Region_education_0.merge(Region_education_1,left_on="Region",right_on="Region")
    

    请注意,在这种情况下,您将有一个包含 Nan 的表,其中无法合并,在您的情况下,Melanesia 将在 Higher Formal Education 列中有一个 Nan。为了避免问题,您可以使用此设置默认值

    Region_education_combined["Higher Formal Education"].fillna(0, inplace=True)
    

    【讨论】:

    • 像魅力一样工作谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    相关资源
    最近更新 更多