gpt4 book ai didi

python - 如何在 Python 数据框中同时替换多行?

转载 作者:太空宇宙 更新时间:2023-11-04 08:25:05 25 4
gpt4 key购买 nike

我有一个数据集,其中一列具有以下唯一值。

   df['Gender'].unique()

array(['Female', 'M', 'Male', 'male', 'm', 'Male-ish', 'maile',
'Trans-female', 'Cis Female', 'something kinda male?', 'Cis Male',
'queer/she/they', 'non-binary', 'Make', 'Nah', 'All', 'Enby',
'fluid', 'Genderqueer', 'Androgyne', 'Agender', 'Guy (-ish) ^_^',
'male leaning androgynous', 'Male ', 'Man', 'msle', 'Neuter',
'queer', 'A little about you', 'Malr',
'ostensibly male, unsure what that really means')]

如您所见,在某些情况下,某行应列为“Male”(当然,我指的是“Male”拼写错误的情况)。如何在不调用替换函数十次的情况下将这些值替换为“男性”?这是我试过的代码:

x=0
while x<=11:
for i in df['Gender']:
if i[0:2]=='Ma':
print('Male')
elif i[0]=='m':
print('Male')
x+=1

然而,我只是得到了一堆“男性”的打印品。

编辑:我想将以下值转换为“男性”:“M”、“男性”、“m”、“maile”、“Make”、“Man”、“msle”、“Malr”、“男性'

最佳答案

创建一个包含男性所有昵称的列表:

males_list = ['M', 'male', 'm', 'maile', 'Make', 'Man', 'msle', 'Malr', 'Male ']

然后将它们替换为:

df.loc[df['Gender'].isin(males_list), 'Gender'] = 'Male'

顺便说一句:总有比在 pandas 中循环行更好的解决方案,不仅仅是在这种情况下。

关于python - 如何在 Python 数据框中同时替换多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58079386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com