Using Dataframe cell values to style another Dataframe with same dimensions

你离开我真会死。 提交于 2019-12-24 00:56:32

问题


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?


回答1:


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)



来源:https://stackoverflow.com/questions/54330809/using-dataframe-cell-values-to-style-another-dataframe-with-same-dimensions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!