I have the following dataframe:
d = {'col1':['b',''], 'col2':['','a'], 'col3':['','']}
index = ['name1','name2']
df = pd.DataFrame(index=index, data=d)
df
col1 col2 col3
name1 b
name2 a
My goal is to have something like this:
col1 col2 col3
name1 green red yellow
name2
I need help with the logic of renaming the columns.
Rename only row 1.
if a-z in row 1 than 'green'
elif a-z in row 2 than 'red'
elif both rows empty than 'yellow'
What I tried is the following, but it only changes one color.
df.replace({'[a-z]':'green'},regex=True)
Could anyone help me solve this problem?
CodePudding user response:
Use:
a = df.loc['name1'].replace({'[a-z]':'green', '':np.nan},regex=True)
b = df.loc['name2'].replace({'[a-z]':'red', '':np.nan},regex=True)
df.loc['name1'] = a.fillna(b).fillna('yellow')
print (df)
col1 col2 col3
name1 green red yellow
name2 a
df.loc['name2','col2'] = ''
print (df)
col1 col2 col3
name1 green red yellow
name2