0
Male_Female = users[['occupation','gender','age']]
Male_Female

Output

occupation  gender  age
0   technician  M   24
1   other   F   53
2   writer  M   23
3   technician  M   24
4   other   F   33

I need to convert the string from M=1, F=0

Male_Female_numeric = Male_Female(np.where((users['gender'] == 'M'), 1, 0)) Male_Female_numeric

I got error

TypeError: 'DataFrame' object is not callable

Disclaimer: I got the output with the below code

def gender_to_numeric(x):
    if x == 'M':
        return 1
    if x == 'F':
        return 0

users['gender_n'] = users['gender'].apply(gender_to_numeric)

How to achieve the same output using np.where

  • just use: `users['gender_n']=np.where((users['gender'] == 'M'), 1, 0)` – anky Jan 01 '20 at 06:45
  • @anky_91 then i will get array([1, 0, 1, 1, ....]] –  Jan 01 '20 at 06:47
  • yes, assign back to the original frame as a series. see my comment above – anky Jan 01 '20 at 06:47
  • also you can use: `users['gender_n']=users['gender_n'].eq('Male').astype(int)` – anky Jan 01 '20 at 06:49
  • @anky_91 `SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead` got above error –  Jan 01 '20 at 06:55
  • 1
    that is because the Male_Female df is referred from the original df. use `Male_Female = users[['occupation','gender','age']].copy()` first and then `Male_Female['gender_n']=np.where((Male_Female['gender'] == 'M'), 1, 0)` , read [this](https://stackoverflow.com/questions/20625582/how-to-deal-with-settingwithcopywarning-in-pandas) – anky Jan 01 '20 at 06:57

0 Answers0