1
df2 = np.where(df2['color'] != 'blue' | 'red')

I want to create one category for many categorical values, such as:

If the color is not blue or red, call the color "other"

Please and thank you <3

Progman
  • 16,827
  • 6
  • 33
  • 48
bowen_eldr
  • 13
  • 2
  • `df['color'] = np.where(df['color'].isin(['blue', 'red']), df['color'], 'Other')` as [jezrael recommends](https://stackoverflow.com/a/51323112/15497888) – Henry Ecker Nov 08 '21 at 20:35

1 Answers1

1

You are basically halfway there. You just have to provide 2 more parameters to achieve what you want.

df2['color'] = np.where((df2['color'] == 'blue') | (df2['color'] == 'red'), df2['color'], 'other')

Reading the equality is easier because there is less cognitive load. If the condition is True the df2['color'] will be selected. If the condition is false for that row 'other' will be selected

alparslan mimaroğlu
  • 1,450
  • 1
  • 10
  • 20