Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (47.6k points)

I have a dataframe along the lines of the below:

   Type  Set 

1 A   Z 

2 B   Z 

3 B     X 

4 C     Y

I want to add another column to the dataframe (or generate a series) of the same length as the dataframe (= equal number of records/rows) which sets a colour green if Set = 'Z' and 'red' if Set = otherwise.

What's the best way to do this?

1 Answer

0 votes
by (106k points)

For pandas conditional creation of a series/dataframe column you can use the below-mentioned code:-

import pandas as pd 

import numpy as np 

df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')})

df['color'] = np.where(df['Set']=='Z', 'green', 'red') 


Browse Categories