Reputation: 471
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo'.split(),
'B': 'one one two'.split(),
'C': np.arange(3), 'D': np.arange(3) * 2})
j = [{'bgcolor': "#55aa2a"}, {'bgcolor': "#d42a2a"}, {'bgcolor': "#d42a2a"}]
df2 = pd.DataFrame({'E': j, 'F': j, 'G': j, 'H': j})
The code above produces two dataframes, df1
is a standard frame and df2
is a frame composed of dictionaries (each cell has a dictionary as its value).
I want to use the cells of df2
to style the cells of df
in place, i.e. the cell df[0,1]
will take the value of cell df2[0,1]
and use it as its style
Example:
def highlight(df,df2):
df[0,1] = '{}'.format(df2[0,1])
return df
(except applied to the entire frame)
This should give the background color of df[0,1]
as df2[0,1]="55aa2a"
but returns a KeyError
after calling df = df.style.apply(highlight, df2=df2).render()
Is it possible to use the cells of df2
to style the cells of df1
?
Upvotes: 2
Views: 1709
Reputation: 862611
You can change format of values for strings and then return DataFrame with same columns names (index values is necessary same too):
df2 = df2.applymap(lambda x: 'background-color: {}'.format(x.get('bgcolor')))
print (df2)
E F \
0 background-color: #55aa2a background-color: #55aa2a
1 background-color: #d42a2a background-color: #d42a2a
2 background-color: #d42a2a background-color: #d42a2a
G H
0 background-color: #55aa2a background-color: #55aa2a
1 background-color: #d42a2a background-color: #d42a2a
2 background-color: #d42a2a background-color: #d42a2a
def highlight(x):
d = dict(zip(df2.columns, x.columns))
return df2.rename(columns=d)
Or:
def highlight(x):
return pd.DataFrame(df2.values, columns=x.columns)
df.style.apply(highlight, axis=None)
Upvotes: 3