【问题标题】:Create multiple, new columns from dict values by mapping against a single column通过映射到单个列从 dict 值创建多个新列
【发布时间】:2018-09-18 08:14:20
【问题描述】:

此问题与有关通过使用字典进行映射/查找来创建新列的帖子有关。 (Adding a new pandas column with mapped value from a dictionarypandas - add new column to dataframe from dictionary)。但是,如果我想创建多个具有字典值的新列,该怎么办。

为了论证,假设我有以下df:

   country   
0  bolivia   
1  canada  
2  ghana    

在不同的数据框中,我有国家映射:

country   country_id   category  color
0  canada    11        north     red
1  bolivia   12        central   blue
2  ghana     13        south     green

我一直在使用 pd.merge 将映射数据框合并到我的 df,使用国家和另一个索引作为键,它基本上可以完成这项工作,这给了我想要的输出:

   country   country_id  category  color
0  bolivia   12          central   blue
1  canada    11          north     red
2  ghana     13          south     green

但是,最近,我一直想尝试使用字典。我想一个相关的问题是如何确定使用pd.merge 或字典来完成我的任务。

对于我将映射的一次性列,我将通过映射到字典来创建一个新列:

country_dict = dict(zip(country, country_id))    
df['country_id'] = df['country'].map(entity_dict)

定义一个接收不同字典并分别创建每个新列的函数似乎不切实际(例如,dict(zip(key, value1)), dict(zip(key, value2)))。我被困在如何同时创建多个列上。我重新开始,并尝试将国家映射 Excel 工作表创建为字典:

entity_dict = entity.set_index('country').T.to_dict('list')

然后从那里,将 dict 值转换为列:

entity_mapping = pd.DataFrame.from_dict(entity_dict, orient = 'index')
entity_mapping.columns = ['col1', 'col2', 'col3']

在过去的几天里,我一直在兜圈子。任何帮助/反馈将不胜感激!

【问题讨论】:

  • 我有点困惑。如果您有要合并到数据框的字典,为什么不将字典转换为数据框然后执行合并?听起来您想要一种绕过pd.merge() 的替代方法,但由于这似乎是最直接的方法,我不确定如何提供答案。
  • 使用 pd.merge() 可能是最直接的情况,但我只是想确保没有其他更有意义的方法。

标签: python pandas dictionary mapping


【解决方案1】:

好的,在解决这个问题之后......我想 pd.merge 最有意义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    • 2017-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多