如何将背景颜色添加到熊猫数据框的特定列并将该彩色数据框保存到同一个 csv 中?

kal*_*wal 2 python csv dataframe python-3.x pandas

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

带有彩色列的示例数据

piR*_*red 6

我强烈建议阅读文档中指南
要查看列名样式的示例,请参阅Scott Boston 的这篇文章


styleapply

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'])
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)

在此处输入图片说明


另存为 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())
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明