gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:35:38 29 4
gpt4 key购买 nike

我有一个 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com