我有一个 CSV 文件,我添加了代码来处理其中的数据,并知道如何使用 to_csv
方法将最终数据帧保存到同一个 CSV 中。问题是我想为某些列添加背景颜色,我该怎么做?
最佳答案
我强烈建议阅读guide in the docs
要查看列名称样式的示例,请参阅 this post by Scott Boston
样式
与应用
df = pd.DataFrame([[0, 1], [2, 3]], ['A', 'B'], ['X', 'Y'])
def f(dat, c='red'):
return [f'background-color: {c}' for i in dat]
df.style.apply(f, axis=0, subset=['X'])
<小时/>
多色
columns_with_color_dictionary = {'X': 'green', 'Y': 'cyan'}
style = df.style
for column, color in columns_with_color_dictionary.items():
style = style.apply(f, axis=0, subset=column, c=color)
style
<小时/>
在列名称中保存颜色元数据
df.rename(columns=lambda x: f"{x}_{columns_with_color_dictionary.get(x)}") \
.to_csv('colorful_df.csv')
df_color = pd.read_csv('colorful_df.csv', index_col=0)
cmap = dict([c.split('_', 1) for c in df_color])
df_color.columns = df_color.columns.str.split('_', 1).str[0]
style = df_color.style
for column, color in cmap.items():
style = style.apply(f, axis=0, subset=column, c=color)
style
<小时/>
另存为HTML
from IPython.display import HTML
columns_with_color_dictionary = {'X': 'yellow', 'Y': 'orange'}
style = df.style
for column, color in columns_with_color_dictionary.items():
style = style.apply(f, axis=0, subset=column, c=color)
with open('df.html', 'w') as fh:
fh.write(style.render())
HTML(open('df.html').read())
关于python - 如何将背景颜色添加到 pandas 数据框的特定列并将该彩色数据框保存到同一个 csv 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57805803/