如何用pandas中to_excel添加颜色

发布时间:2020-07-15 11:30:11 作者:清晨
来源:亿速云 阅读:2419

小编给大家分享一下如何用pandas中to_excel添加颜色,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!

我就废话不多说了,大家还是直接看代码吧~

import pandas as pd
import numpy as np
 
columns = [['A', 'A', 'B', 'B', 'C'], ['a', 'b', 'c', 'd', 'e']]
# 创建形状为(10,5) 的DataFrame 并设置二级标题
demo_df = pd.DataFrame(np.arange(50).reshape(10, 5), columns=columns)
print(demo_df)
 
def style_color(df, colors):
  """
  
  :param df: pd.DataFrame
  :param colors: 字典 内容是 {标题:颜色}
  :return: 
  """
  return df.style.apply(style_apply, colors=colors)
 
def style_apply(series, colors, back_ground=''):
  """
  :param series: 传过来的数据是DataFramt中的一列  类型为pd.Series
  :param colors: 内容是字典 其中key 为标题名  value 为颜色
  :param back_ground: 北京颜色
  :return:
  """
  series_name = series.name[0]
  a = list()
  # 为了给每一个单元格上色
  for col in series:
    # 其中 col 为pd.DataFrame 中的 一个小单元格  大家可以根据不同需求为单元格设置不同的颜色
    # 获取什么一级标题获取什么颜色
    if series_name in colors:
      for title_name in colors:
        if title_name == series_name:
          back_ground = 'background-color: ' + colors[title_name]
          # '; border-left-color: #080808'
    a.append(back_ground)
  return a
 
style_df = style_color(demo_df, {"A": '#1C1C1C', "B": '#00EEEE', "C": '#1A1A1A'})
 
with pd.ExcelWriter('df_style.xlsx', engine='openpyxl') as writer:
  #注意: 二级标题的to_excel index 不能为False
  style_df.to_excel(writer, sheet_name='sheet_name')

以上就是pandas.DataFrame 二级标题to_excel() 添加颜色的demo 大家可以自行根据不同需求修改

主要注意

style_apply 方法中的内容 里面是真正设置颜色的地方

补充知识:对pandas的dataframe自定义颜色显示

原始表是这样,一堆数字视觉表达能力很差

如何用pandas中to_excel添加颜色

quantity_year.style.background_gradient(cmap='gray_r')

如何用pandas中to_excel添加颜色

按照大小对其进行不同颜色的填充,视觉表达能力强了很多。 也可以自定义颜色填充,比如我这里对大于平均值的进行颜色填充。

quantity_year.style.applymap(lambda v
               : 'background-color: %s' %'#FFCCFF' if v>quantity_year.mean().mean() 
               else'background-color: %s'% '')

当然也可以自己def 更复杂的功能,都是大同小异。当然还有highlight_max(‘color'),highlight_min(‘color')这种高亮最小最大值,也有hide_index()这种隐藏索引的小操作,在这里记录一下。

看完了这篇文章,相信你对如何用pandas中to_excel添加颜色有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

推荐阅读:
  1. 如何用用fieldset设置边框颜色
  2. pandas中read_excel()和to_excel()函数的作用是什么

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

pandas to excel 颜色

上一篇:Spring Boot Actuator 整合 Prometheus

下一篇:数据分析用它就够了 | 37 个场景告诉你为什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》