kal*_*wal 2 python csv dataframe python-3.x pandas
我有一个 CSV 文件,我添加了代码以处理其上的数据,并知道如何使用to_csv方法将最终数据帧保存到同一个 CSV 。问题是我想为某些列添加背景颜色,我该怎么做?

我强烈建议阅读文档中的指南
要查看列名样式的示例,请参阅Scott Boston 的这篇文章
style 和 applydf = 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'])
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
HTMLfrom 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())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3833 次 |
| 最近记录: |