如何将背景色添加到pandas数据框的特定列并将该彩色数据框保存到相同的csv中? [英] How to to add Background color to a specific column of pandas dataframe and save that colored dataframe into that same csv?
本文介绍了如何将背景色添加到pandas数据框的特定列并将该彩色数据框保存到相同的csv中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个CSV文件,我添加了代码来处理其上的数据,并且知道如何使用 to_csv
方法将最终数据帧保存到同一CSV中。问题是我想将背景色添加到某些列中,该怎么做?
解决方案
我强烈建议阅读
多色
columns_with_color_dictionary = {'X':'green','Y':'cyan'}
style = df.style
用于列,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 df_color中的c])
df_color.columns = df_color.columns.str.split(' _',1).str [0]
style = df_color.style
用于列,颜色在cmap.items()中:
style = style.apply(f,axis = 0,subset = column,c = color)
style
另存为 HTML
从IPython.display import HTML
columns_with_color_dictionary = {'X':'黄色','Y':'橙色'}
style = df.style
用于列,颜色在columns_with_color_dictionary中。 items():
style = style.apply(f,axis = 0,subset = column,c = color)
以open('df.html','w')为fh:
fh.write(style.render())
HTML(open('df.html')。read())
I have a CSV file I add the code to process data on it and know how to save the final dataframe to the same CSV by using to_csv
method. The problem is I want to add the background color to some of the columns, how can I do it?
解决方案
I strongly suggest reading the guide in the docs
To see an example where column names are styled see this post by Scott Boston
style
with apply
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'])
Multicolor
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
Save color meta data in the column name
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
Save as 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())
这篇关于如何将背景色添加到pandas数据框的特定列并将该彩色数据框保存到相同的csv中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文