0

I need to add a new column to a DataFrame where I need to add values by condition. There are only three values in the df['name'] column: 'Enable', 'Disable', NaN. I try to use -> if else, how to change below line of code to use if elif else where:

if df['name'] == 'Enable' then df['status'] = 1, if df['name'] == 'Disable' then df['status'] = 0, if df['name'] == NaN then df['status'] = 2

How to change this part of the code for three values, thanks?

df['status'] = [0 if i == 'Disable' else 1 for i in df['name']]

this case -> Pandas conditional creation of a series/dataframe column not resolve my problem and this is not show how to use if elif else, this case has only two different values.

Alex
  • 147
  • 8
  • Check `np.select`, for test missing values use `mask = df['name'].isna()` – jezrael Jul 04 '22 at 12:39
  • @jezrael, hi, it's not good way for me. For example, instead of Nan there will be a string value like 'empty'. I need to resolve this use if elif else if it is possible – Alex Jul 04 '22 at 12:43
  • Do you check `np.select` ? If empty string use `mask = df['name'] == 'empty'` – jezrael Jul 04 '22 at 12:45
  • I fix it like this -> df['status'] = np.nan; df['status'] = df['status'].mask(df['name'] == 'Enabled', 1).mask(df['name'] == 'Disabled', 0).mask(df['name'].isna(), 2) – Alex Jul 04 '22 at 14:39

0 Answers0