How do I add a color
column to the following dataframe so that color='green'
if Set == 'Z'
, and color='red'
otherwise?
Type Set
1 A Z
2 B Z
3 B X
4 C Y
dataframenumpypandaspython
How do I add a color
column to the following dataframe so that color='green'
if Set == 'Z'
, and color='red'
otherwise?
Type Set
1 A Z
2 B Z
3 B X
4 C Y
Best Answer
If you only have two choices to select from then use
np.where
:For example,
yields
If you have more than two conditions then use
np.select
. For example, if you wantcolor
to beyellow
when(df['Set'] == 'Z') & (df['Type'] == 'A')
blue
when(df['Set'] == 'Z') & (df['Type'] == 'B')
purple
when(df['Type'] == 'B')
black
,then use
which yields