简体   繁体   English

如何使用基于条件的值将 append 列到 dataframe

[英]How to append a column to a dataframe with values based on condition

I have the following dataframe:我有以下 dataframe:

Country is actually the index: Country 实际上是索引:

       2014          2015        PopEst  
Country                                                       
China               8.230121e+12  8.797999e+12  1.367645e+09  
United States       1.615662e+13  1.654857e+13  3.176154e+08  
Japan               5.642884e+12  5.669563e+12  1.274094e+08  
United Kingdom      2.605643e+12  2.666333e+12  6.387097e+07  
Russian Federation  1.678709e+12  1.616149e+12  1.435000e+08  
Canada              1.773486e+12  1.792609e+12  3.523986e+07  
Germany             3.624386e+12  3.685556e+12  8.036970e+07  
India               2.200617e+12  2.367206e+12  1.276731e+09  
France              2.729632e+12  2.761185e+12  6.383735e+07  
South Korea         1.234340e+12  1.266580e+12  4.980543e+07  
Italy               2.033868e+12  2.049316e+12  5.990826e+07  
Spain               1.375605e+12  1.419821e+12  4.644340e+07  
Iran                4.639027e+11           NaN  7.707563e+07  
Australia           1.272520e+12  1.301251e+12  2.331602e+07  
Brazil              2.412231e+12  2.319423e+12  2.059153e+08

And I have the following dict:我有以下听写:

ContinentDict  = {'China':'Asia', 
                  'United States':'North America', 
                  'Japan':'Asia', 
                  'United Kingdom':'Europe', 
                  'Russian Federation':'Europe', 
                  'Canada':'North America', 
                  'Germany':'Europe', 
                  'India':'Asia',
                  'France':'Europe', 
                  'South Korea':'Asia', 
                  'Italy':'Europe', 
                  'Spain':'Europe', 
                  'Iran':'Asia',
                  'Australia':'Australia', 
                  'Brazil':'South America'}

I need to append a column showing the Continent Name for each country.我需要 append 列显示每个国家/地区的大陆名称。

how can I do this?我怎样才能做到这一点?

Use:利用:

df['Continent'] = df.index.map('ContinentDict')

Try this:尝试这个:

df['Continent'] = df.apply(lambda row : ContinentDict[row.name]  ,axis = 1)

Output: Output:

              2014           2015           PopEst           Continent
China         8.230121e+12  8.797999e+12    1.367645e+0       Asia
United States 1.615662e+13  1.654857e+13    3.176154e+0       North America

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

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