pandas 数据框中的颜色单元格
我有一个具有不同值的数据框,但是大多数tham是NaN(无).我想为值不是None的单元格着色,而值实际上是值. 例如:dataxml =
I have a dataframe with different values, but most of tham are NaN (None). I want to colour cells where value is not a None, where is actually value. For example: dataxml=
1 2 3 4 5
a NaN 23 NaN NaN 65
b NaN NaN 54 NaN NaN
c 33 NaN NaN NaN NaN
d NaN NaN 24 NaN NaN
此代码为整个数据框上色:
This code color whole dataframe:
def highlight_cells(value):
if value != None:
return 'background-color: yellow'
dataxml.style.applymap(highlight_cells)
据我所知,df.style
仅在将数据框导出为HTML时使用.
As far as I know, df.style
is only used when exporting the dataframe to HTML.
对于Excel,如果我建议使用编写的库,请参见以下示例代码(请注意,由于使用整数作为标题存在一个小问题,因此此列标题使用了字符串):
For Excel, If I may suggest using a library that I wrote, see this example code (Note that this is using strings for the column headers since there is a small issue with using integers as headers):
import pandas as pd
from StyleFrame import StyleFrame, Styler
df = pd.DataFrame({'1': [None, None, 33, None],
'2': [23, None, None, None],
'3': [None, 54, None, 24]})
sf = StyleFrame(df)
style = Styler(bg_color='yellow')
for col_name in df.columns:
sf.apply_style_by_indexes(sf[~df[col_name].isnull()], cols_to_style=col_name,
styler_obj=style)
sf.to_excel('test.xlsx').save()
这将生成以下Excel:
This generates the following Excel: