繁体   English   中英

根据其他列(python)中的分类值创建新的pandas列

[英]Create new pandas column based on categorical values in other column (python)

我有一个包含国家/地区和流量列的数据框:

Country    |   Traffic
  US            8687
  Italy         902834
  Germany       2343
  Brazil        4254
  France        23453

我想在此数据框中添加一个名为“Region”的第三列。 它看起来像这样:

 Country    |   Traffic   | Region
  US            8687         US
  Italy         902834       EU
  Germany       2343         EU
  Brazil        4254         LA
  France        23453        EU

如果我只有两个区域,则以下代码有效。 我正在寻找更多if/elsemaplambda语句:

df['Region'] = np.where(df['Country'] == 'US', 'US', 'EU')

谢谢。

你可以使用字典:

region_from_country = {
    'US': 'US', 
    'Italy': 'EU',
    'Germany': 'EU',
    'Brazil': 'LA', 
    'France': 'EU',
}
df['Region'] = df['Country'].replace(region_from_country)

字典中的键是国家,值是相应的区域。

一个简单的方法是:

dict ={'US':'US','Italy':'EU','Germany':'EU','Brazil':'LA','France':'EU'}

df['Region']=df['Country'].apply(lambda x : dict[x])

暂无
暂无

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

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