【问题标题】:How to to add Background color to a specific column of pandas dataframe and save that colored dataframe into that same csv?如何将背景颜色添加到熊猫数据框的特定列并将该彩色数据框保存到同一个 csv 中?
【发布时间】:2020-01-08 09:00:03
【问题描述】:

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

【问题讨论】:

  • csv 不保存有关列的颜色信息。您需要将颜色信息另存为另一列或列名中,并使用自定义 csv 阅读器将其解析出来。我想说的是 csv 不会做你想做的事,为了让它做它无论如何,它会变得丑陋。
  • 你能告诉我如何为包括 column_name 在内的整个特定列添加颜色,它是数据框的所有值?表示如何在 Dataframe 中获得提及的图像,如输出
  • 尝试使用/谷歌搜索pd.ExcelWriter,将结果保存为 .xlsx 将允许您为列背景着色。

标签: python python-3.x pandas csv dataframe


【解决方案1】:

我强烈建议阅读guide in the docs
要查看列名样式的示例,请参阅this post by 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'])


多色

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())

【讨论】:

  • 我尝试了上面的代码,但是当我打印时,pycharm 给了我一个正常的数据框,而不是像你在 IDLE 中显示的一样颜色的 df
猜你喜欢
  • 2020-05-15
  • 2021-07-03
  • 2018-12-01
  • 1970-01-01
  • 2019-05-21
  • 2017-01-04
  • 1970-01-01
  • 2016-09-08
  • 1970-01-01
相关资源
最近更新 更多