How can I change values of data with condition in Python?

Viewed 61

I'm not sure how to explain my problem.. But I have a series that looks like this:

0 Male 
1 Female                   
2 male                                       
3 M                                        
4 m                                  
5 LGBT                                   
6 Others                           
7 Make                          
8 Male                              
9 Man                                
10 Cis Male 

And I'm trying to narrow it down to:

Male
Female
Others
LGBT

I was able to narrow it down using:

LGBT = survey['Gender'].str.contains('Trans|Neuter|queer|andro|Andro|Enby|binary|trans')
survey.loc[LGBT, 'Gender'] = 'LGBT'

Others = survey['Gender'].str.contains('N|A|p')
survey.loc[Others, 'Gender'] = 'Others'

Female = survey['Gender'].str.contains('F|Wo|f|wo')
survey.loc[Female, 'Gender'] = 'Female'

For each section, but now I'm trying to have the rest of the items into 'Male', I'm not able to do so. I tried using Regex but because 'Female' also contains 'm', it just changes everything to Male...

How can I solve this problem? What kind of function should I look into? I tried eq such as below:

survey['Gender'].eq(['Male', 'Female', 'Others', 'LGBT']).map({False: 'Male'})

But it gave me an error of:

ValueError: Lengths must be equal

And I'm getting more confused.... Any advice and help will be appreciated!

1 Answers

You can use pandas.Series.isin, which is useful when you want to compare multiple values at the same time.

Male = ~survey['Gender'].isin(['Female', 'Others', 'LGBT'])
survey.loc[Male, 'Gender'] = 'Male'

Since you have already narrowed down the other cases, you can just check if the elements are equal to any of the previously set (Female, Others, LGBT) and, if not, you set them as Male.

Related