Skip to main content
 首页 » 编程设计

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

2025年05月04日17thcjp

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

   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 中循环行更好的解决方案,不仅仅是在这种情况下。