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

标签 python python-3.x pandas csv dataframe

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

Example data with colored columns

最佳答案

我强烈建议阅读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'])

enter image description here

<小时/>

多色

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

enter image description here

<小时/>

在列名称中保存颜色元数据

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

enter image description here

<小时/>

另存为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())

enter image description here

关于python - 如何将背景颜色添加到 pandas 数据框的特定列并将该彩色数据框保存到同一个 csv 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57805803/

相关文章:

python - 在 AWS Lambda 中连接 AWS RDS (psql)

python - 面对python继承中的问题

python - AttributeError: 'module' object has no attribute 'HOUGH_GRADIENT' , cv.HOUGH_GRADIENT 没有解决这个问题

Python MySQLdb 文件加载截断行,从另一个 mysql 客户端加载文件时工作正常

python - DJANGO 静态图像不显示在模板中

python - 从 C 导入标准 Python 库

python - 根据另一个系列索引从数据框中选择行

python - 使用 Pandas DataFrame.sort() 时,我可以让它真正对行重新编号吗?

python - 指定日期时间周数格式

python - 有效地将长度为 n 的列表的 pandas 数据帧转换为 n 个数据帧