【问题标题】:Combining 3 data frames based on common field 'Country'基于公共字段“国家”组合 3 个数据帧
【发布时间】:2019-07-13 02:33:27
【问题描述】:

我有 3 个具有共同国家索引的数据框。我需要根据该 Country 字段组合这 3 个中的每一个。

我的第一次尝试是结合两个,然后是第三个,这就是我得到的结果:

pd.merge(energy, GDP, how='outer', left_index=True, right_index=True)

我尝试了 3 个在此网站上获得高度评价的选项:

import functools
dfs = [energy, GDP, ScimEn]
df_final = functools.reduce(lambda left,right: pd.merge(left,right,on='Country'), dfs)
energy.merge(GDP,on='Country').merge(ScimEn,on='Country')
pd.concat([energy.set_index('Country'), GDP.set_index('Country'), ScimEn.set_index('Country')], axis=1)

KeyError: '国家'

在处理上述异常的过程中,又发生了一个异常:

密钥错误
Traceback(最近一次通话最后一次) 在 () 40 #df_final = functools.reduce(lambda left,right: pd.merge(left,right,on='Country'), dfs) 41 #energy.merge(GDP,on='Country').merge(ScimEn,on='Country') ---> 42 pd.concat([energy.set_index('Country'), GDP.set_index('Country'), ScimEn.set_index('Country')], axis=1)

【问题讨论】:

  • 您应该始终包含一些数据样本,以便您的错误可以是reproducible
  • pd.concat([x.set_index('Country') for x in dfs], axis=1)?
  • Quang: 我得到错误'str' object has no attribute 'set_index'

标签: python-3.x pandas


【解决方案1】:

您需要进行多次合并。请尝试以下操作:

merge1 = pd.merge(energy, GDP, how='inner', on='Country')
final = pd.merge(merge1, ScimEn, how='inner', on='Country')

【讨论】:

  • 有人建议我分享一些数据,所以这里是: 能源数据框:国家能源供应 人均能源供应百分比 阿富汗可再生能源 321000000 10 78.6693 ScimEn 数据框:国家排名文件可引用文件引用自引用阿富汗 163 3 3 49 0 GDP 数据框 国家 2006 2007 阿富汗 1.030523 X 10 +10 1.172119 X 10 +10
  • 我在“KeyError: 'Country' - 可能是数据类型不一样时不断收到错误消息;我看看能否确认。感谢您的尝试
猜你喜欢
  • 2023-02-13
  • 2020-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-16
  • 1970-01-01
  • 1970-01-01
  • 2020-10-15
相关资源
最近更新 更多