Python 数据帧中的彩色单元
我有一个具有不同值的数据帧,但大多数tham都没有。我想给单元格上色,其中值不是无,实际上是值。 例如:dataxml=Python 数据帧中的彩色单元,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个具有不同值的数据帧,但大多数tham都没有。我想给单元格上色,其中值不是无,实际上是值。 例如: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 此代码为整个数据帧着色: def highlight_
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
此代码为整个数据帧着色:
def highlight_cells(value):
if value != None:
return 'background-color: yellow'
dataxml.style.applymap(highlight_cells)
您可以这样做:
notnull_color = 'yellow'
df.style.applymap(lambda x: 'background-color: %s' % notnull_color if pd.notnull(x) else '')
您可以这样做:
notnull_color = 'yellow'
df.style.applymap(lambda x: 'background-color: %s' % notnull_color if pd.notnull(x) else '')
据我所知,df.style仅在将数据帧导出为HTML时使用
对于Excel,如果我建议使用我编写的库,请参阅此示例代码注意,这是使用字符串作为列标题,因为使用整数作为标题存在一个小问题:
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:
据我所知,df.style仅在将数据帧导出为HTML时使用
对于Excel,如果我建议使用我编写的库,请参阅此示例代码注意,这是使用字符串作为列标题,因为使用整数作为标题存在一个小问题:
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:
您正在生成HTML或Excel文件吗?我已经分析了XML文件,找到了属性值之间的差异,然后转换为pandas dataframe,现在我需要突出显示有差异的单元格,以便在Excel中更容易找到,如果没有差异,则什么也不做。您正在生成HTML或Excel文件吗?我已经分析了XML文件,找到属性值之间的差异,然后转换为pandas dataframe,现在我需要突出显示具有差异的单元格,以便更容易在excel中找到它,如果没有差异,则什么也不做。但我有201行和2105列@DeepSpace@jovicbg请参阅我的更新答案,以了解一般解决方案。行数无关紧要。只是删除了我的行名,Excel中没有第一列,但我有201行和2105列@DeepSpace@jovicbg请参阅我的更新答案,以了解一般解决方案。行数无关紧要。只是删除了我的行名,excel中没有第一列,但我无法将其保存到excel。在新的jupyter手机中运行后,它就消失了。这确实有效,但我无法将它保存到excel。在新的jupyter牢房里运行后就消失了