【问题标题】:Pandas iterate over rows and find the column namesPandas 遍历行并找到列名
【发布时间】:2019-06-28 23:16:32
【问题描述】:

我有两个数据框:

df = pd.DataFrame({'America':["Ohio","Utah","New York"],
                   'Italy':["Rome","Milan","Venice"],
                   'Germany':["Berlin","Munich","Jena"]});


df2 = pd.DataFrame({'Cities':["Rome", "New York", "Munich"],
                   'Country':["na","na","na"]})

我想在 df2 "Cities" 列上查找我 (df) 上的城市并将城市的国家/地区(df 列名称)附加到 df2 国家列

【问题讨论】:

  • 如果我或其他答案有帮助,请不要忘记accept。谢谢。
  • 做到了。感谢您的回答和通知
  • 感谢您的支持,但接受是必要的,请单击以清空下一步9,检查上面评论中的链接。

标签: python pandas loops


【解决方案1】:

通过字典使用meltmap

df1 = df.melt()
print (df1)
  variable     value
0  America      Ohio
1  America      Utah
2  America  New York
3    Italy      Rome
4    Italy     Milan
5    Italy    Venice
6  Germany    Berlin
7  Germany    Munich
8  Germany      Jena

df2['Country'] = df2['Cities'].map(dict(zip(df1['value'], df1['variable'])))
#alternative, thanks @Sandeep Kadapa 
#df2['Country'] = df2['Cities'].map(df1.set_index('value')['variable'])
print (df2)
     Cities  Country
0      Rome    Italy
1  New York  America
2    Munich  Germany

【讨论】:

  • df2['Cities'].map(df1.set_index('value')['variable'])
【解决方案2】:

熔化并重命名第一个数据框后:

df1 = df.melt().rename(columns={'variable': 'Country', 'value': 'Cities'})

解决方案是简单的合并:

df2 = df2[['Cities']].merge(df1, on='Cities')

【讨论】:

    猜你喜欢
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 2019-03-28
    • 2018-10-28
    相关资源
    最近更新 更多