如何在没有地图的情况下替换熊猫数据框中的多个值?

问题描述 投票:1回答:1

我有一个如下所示的数据框

import pandas as pd
df1 = pd.DataFrame({'ethnicity': ['AMERICAN INDIAN/ALASKA NATIVE', 'WHITE - BRAZILIAN', 'WHITE-RUSSIAN','HISPANIC/LATINO - COLOMBIAN',
                                 'HISPANIC/LATINO - MEXICAN','ASIAN','ASIAN - INDIAN','ASIAN - KOREAN','PORTUGUESE','MIDDLE-EASTERN','UNKNOWN',
                                 'USER DECLINED','OTHERS']})

enter image description here

我想替换种族列值。例如:如果值是ASIAN - INDIAN,我想将其替换为ASIAN

类似地,我想替换包含AMERICANWHITEHISPANIC的字符串,将其他字符串替换为others。这就是我正在尝试的]

df1.loc[df.ethnicity.str.contains('WHITE'),'ethnicity'] = "WHITE"
df1.loc[df.ethnicity.str.contains('ASIAN'),'ethnicity'] = "ASIAN"
df1.loc[df.ethnicity.str.contains('HISPANIC'),'ethnicity'] = "HISPANIC"
df1.loc[df.ethnicity.str.contains('AMERICAN'),'ethnicity'] = "AMERICAN"
df1.loc[df.ethnicity.str.contains(other ethnicities),ethnicity] = "Others" # please note here I don't know how to replace all other ethnicities at once as others

我希望我的输出如下所示

enter image description here

python python-3.x pandas dataframe str-replace
1个回答
2
投票

通过列表的值使用Series.str.extract,并且为了匹配而返回Series.str.extract s,因此添加NaN

Series.fillna

或者您可以在字符串中加入valeus:

Series.fillna

L = ['WHITE','ASIAN','HISPANIC','AMERICAN']

print (f'({"|".join(L)})')
(WHITE|ASIAN|HISPANIC|AMERICAN)

df1.ethnicity = df1.ethnicity.str.extract(f'({"|".join(L)})', expand=False).fillna('Others')
© www.soinside.com 2019 - 2024. All rights reserved.