简体   繁体   English

字典中 dataframe 列中的 python - Map 值,列表为值

[英]python - Map values in dataframe columns from dictionary with list as value

I am trying to map values to dataframe columns from a dictionary.我正在尝试将 map 值转换为字典中的 dataframe 列。 Here is the code:这是代码:

# 
import pandas as pd
region_dict = {'Russia':['Europe','Eastern Europe'], 
               'South Korea':['Asia','Easter Asia'],
               'Iran':['Asia','Southern Asia'], 
               'North Korea':['Asia','Eastern Asia']}
region_dict
#> {'Russia': ['Europe', 'Eastern Europe'],
   'South Korea': ['Asia', 'Eastern Asia'],
   'Iran': ['Asia', 'Southern Asia'],
   'North Korea': ['Asia', 'Eastern Asia']}
    
df = pd.DataFrame({'Country':['Russia', 'Iran', 'South Korea','USA'],
                   'continent':['NaN','NaN','NaN','Americas'],
                   'sub_region':['NaN','NaN','NaN','Northern America']})
df
#>      Country  continent        sub_region
0       Russia         NaN               NaN
1         Iran         NaN               NaN
2  South Korea         NaN               NaN
3          USA    Americas  Northern America

Desired Output:所需的 Output:

#>      Country  Continent  Sub_region
0       Russia   Europe     Eastern Europe  
1         Iran   Asia       Southern Asia
2  South Korea   Asia       Eastern Asia
3          USA   NaN        NaN

I tried我试过了

df[['continent','sub_region']] = df['country'].map(region_dict)

***Error***
ValueError: shape mismatch: value array of shape (20036,) could not be broadcast to indexing result of shape (2,20036)

This way works when the dictionary is in the form当字典在表单中时,这种方式有效

region_dict = {'Russia':'Asia'}

and I map as和我 map 作为

df['continent'] = df['country'].map(region_dict)

Questions问题

  1. How to map multiple columns from a dictionary having list of multiple items as values?如何从具有多个项目列表作为值的字典中 map 多列?
  2. If I want to add only the sub_region column to the df and want to add region_dict['Russia'][1] to the df column, how shall I do it?如果我只想将 sub_region 列添加到 df 并想将region_dict['Russia'][1]添加到 df 列,我该怎么做?

You should convert the mapped series of lists to a df and then assign:您应该将映射的一系列列表转换为 df,然后分配:

df[['continent','sub_region']] = pd.DataFrame(df['Country'].map(region_dict).tolist())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM