Question

I have a dataframe that I am trying to update the sex column with the Gender column

import pandas as pd
import numpy as np

df=pd.DataFrame({'Users': [ 'Al Gore', 'Ned Flonders', 'Kim jong un', 'Al Sharpton', 'Michele', 'Richard Johnson', 'Taylor Swift', 'Alf pig', 'Dick Johnson', 'Dana Jovy'],
                 'Gender': [np.nan,'Male','Male','Male',np.nan,np.nan, 'Female',np.nan,'Male','Female'],
                 'Sex': ['M',np.nan,np.nan,'M','F',np.nan, 'F',np.nan,np.nan,'F']})

Output

>>> 
   Gender  Sex            Users
0     NaN    M          Al Gore
1    Male  NaN     Ned Flonders
2    Male  NaN      Kim jong un
3    Male    M      Al Sharpton
4     NaN    F          Michele
5     NaN  NaN  Richard Johnson
6  Female    F     Taylor Swift
7     NaN  NaN          Alf pig
8    Male  NaN     Dick Johnson
9  Female    F        Dana Jovy

[10 rows x 3 columns]

So if it is male in the "Gender" Column it would show as M in the sex column.

So far here is what I attempted:

df['Sex2']=(df.Gender.isin(['Male']).map({True:'M',False:''}) +
                df.Sex.isin(['M']).map({True:'M',False:''}) +
                df.Sex.isin(['F']).map({True:'F',False:''})+
                df.Gender.isin(['Female']).map({True:'F',False:''}))

print(df)

output

[10 rows x 3 columns]
   Gender  Sex            Users Sex2
0     NaN    M          Al Gore    M
1    Male  NaN     Ned Flonders    M
2    Male  NaN      Kim jong un    M
3    Male    M      Al Sharpton   MM
4     NaN    F          Michele    F
5     NaN  NaN  Richard Johnson     
6  Female    F     Taylor Swift   FF
7     NaN  NaN          Alf pig     
8    Male  NaN     Dick Johnson    M
9  Female    F        Dana Jovy   FF

[10 rows x 4 columns]

I almost got it but this might not be too efficient

Here is what I would like as the output

>>> 
   Gender  Sex            Users
0     NaN    M          Al Gore
1    Male    M     Ned Flonders
2    Male    M      Kim jong un
3    Male    M      Al Sharpton
4     NaN    F          Michele
5     NaN  NaN  Richard Johnson
6  Female    F     Taylor Swift
7     NaN  NaN          Alf pig
8    Male    M     Dick Johnson
9  Female    F        Dana Jovy

[10 rows x 3 columns]

Is it possible to use some merge or update function to do this?

Was it helpful?

Solution

Use map:

In [14]:

import pandas as pd
import numpy as np

df=pd.DataFrame({'Users': [ 'Al Gore', 'Ned Flonders', 'Kim jong un', 'Al Sharpton', 'Michele', 'Richard Johnson', 'Taylor Swift', 'Alf pig', 'Dick Johnson', 'Dana Jovy'],
                 'Gender': [np.nan,'Male','Male','Male',np.nan,np.nan, 'Female',np.nan,'Male','Female'],
                 'Sex': ['M',np.nan,np.nan,'M','F',np.nan, 'F',np.nan,np.nan,'F']})

In [15]:

df

Out[15]:

   Gender  Sex            Users
0     NaN    M          Al Gore
1    Male  NaN     Ned Flonders
2    Male  NaN      Kim jong un
3    Male    M      Al Sharpton
4     NaN    F          Michele
5     NaN  NaN  Richard Johnson
6  Female    F     Taylor Swift
7     NaN  NaN          Alf pig
8    Male  NaN     Dick Johnson
9  Female    F        Dana Jovy

[10 rows x 3 columns]

In [16]:

# create a sex dict
sex_map = {'Male':'M', 'Female':'F'}
# update only those where sex is NaN, apply map to gender to fill in values
df.loc[df.Sex.isnull(),'Sex'] = df['Gender'].map(sex_map)
df

Out[16]:

   Gender  Sex            Users
0     NaN    M          Al Gore
1    Male    M     Ned Flonders
2    Male    M      Kim jong un
3    Male    M      Al Sharpton
4     NaN    F          Michele
5     NaN  NaN  Richard Johnson
6  Female    F     Taylor Swift
7     NaN  NaN          Alf pig
8    Male    M     Dick Johnson
9  Female    F        Dana Jovy

[10 rows x 3 columns]

compare performance:

In [21]:
%timeit df['Sex2']=(df.Gender.isin(['Male']).map({True:'M',False:''}) + df.Sex.isin(['M']).map({True:'M',False:''}) + df.Sex.isin(['F']).map({True:'F',False:''})+                df.Gender.isin(['Female']).map({True:'F',False:''}))

100 loops, best of 3: 2.38 ms per loop

In [24]:
%timeit df.loc[df.Sex.isnull(),'Sex'] = df['Gender'].map(sex_map)

1000 loops, best of 3: 1.21 ms per loop

In [27]:
# without the NaN mask which is similar to what you are doing
%timeit df['Sex'] = df['Gender'].map(sex_map)

1000 loops, best of 3: 531 µs per loop

So on this small sample it is faster, for a much larger dataframe it should be significantly faster as it uses cython

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top