首页 > 其他分享 >Pandas导出美化技巧,让你的Excel更出众

Pandas导出美化技巧,让你的Excel更出众

时间:2024-03-13 16:23:34浏览次数:27  
标签:Styler style utils Excel sf horizontal font Pandas 美化

pandasDataFrame可以通过设置参数使得在jupyter notebook中显示的更加美观,
但是,将DataFrame的数据导出excel时,却只能以默认最朴素的方式将数据写入excel

本文介绍一种简单易用,让导出的excel更加美观的方法。

1. 概要

首先,引入一个库StyleFrame,这个库封装 pandasopenpyxl,让我们轻松的设置DataFrame的样式并导出到excel中。

安装很简单:

pip install styleframe

这个库主要包含3个模块:

  1. styleframe:相当于这个库的主入口,它封装了DataFrame对象。
  2. styler:用来单元格的样式。
  3. utils:常用样式元素的辅助类,比如数字和日期格式、颜色和边框类型等。

安装成功之后,下面通过示例看看如何使用。

2. 准备数据

下面示例中使用的数据采集自链家网的真实成交数据。
数据下载地址:https://databook.top/。

导入数据:

import pandas as pd

fp = "D:/data/南京二手房交易/南京建邺区.csv"
df = pd.read_csv(fp)

# 为了简化,只取10条数据来演示导出效果
df = df.head(10)

image.png

3. 行列设置

先看看默认导出excel的效果。

output = "d:\data\output.xlsx"
df.to_excel(output, index=None)

image.png
默认导出的样式就是这样,所有单元格都一样,不管单元格的内容是什么。

3.1. 设置自适应

第一步,我们设置内容自适应(shrink_to_fit),确保每个单元格中的内容能够完整显示。

from styleframe import StyleFrame, Styler, utils

style = Styler(shrink_to_fit=True)
sf = StyleFrame(df, styler_obj=style)

writer = sf.to_excel(output)
writer.close()

image.png
可以看出,StyleFrame的默认导出样式,给有数据的表格加了边框。
使用shrink_to_fit=True样式之后,每个单元格的内容可以完整显示了。

3.2. 设置列宽

从上面的效果,我们发现,所有列的宽度是一样的,无论列中的内容有多长。
我们可以设置某些文字内容比较多列更宽一些。

sf.set_column_width_dict(
    {
        "name": 25,
        "positionInfo": 20,
        "advantage": 15,
        "dealCycleDays": 16,
    }
)

image.png
调整之后,内容看起来更清晰了。

3.3. 设置表头,内容

接下来,我们通过字号对齐方式背景色以及是否加粗来区分表头内容部分。

header_style = Styler(
    bg_color="yellow",
    bold=True,
    font_size=12,
    horizontal_alignment=utils.horizontal_alignments.center,
    vertical_alignment=utils.vertical_alignments.center,
)
content_style = Styler(
    shrink_to_fit=True,
    font_size=8,
    horizontal_alignment=utils.horizontal_alignments.left,
)

sf.apply_column_style(sf.columns, content_style)
sf.apply_headers_style(header_style)

image.png
内容更加紧凑了,表头部分也更突出了。

3.4. 设置行间隔颜色

最后,我们在优化下内容显示部分,用不同的背景色区分奇数行偶数行

row_style = Styler(
    bg_color="#32CD32",
    shrink_to_fit=True,
    font_size=8,
    horizontal_alignment=utils.horizontal_alignments.left,
)

# 计算要设置背景色的行索引
indexes = list(range(1, len(sf), 2))
sf.apply_style_by_indexes(indexes, styler_obj=row_style)

image.png

4. 样式设置

样式设置主要是Styler这个模块提供的功能。
通过Styler类提供的接口,我们可以设置灵活的控制导出的样式。

4.1. 字体

我们给第一行设置不同的字体(font="STKaiti"),看看导出的效果:

first_line_style = Styler(
    shrink_to_fit=True,
    font="STKaiti",
    font_size=14,
    horizontal_alignment=utils.horizontal_alignments.left,
)
sf.apply_style_by_indexes(indexes_to_style=[0], styler_obj=first_line_style)

image.png
第一行的字体是华文楷体,和其他行不一样。

4.2. 颜色

再把第一行的字调成蓝色(font_color="blue")。

first_line_style = Styler(
    shrink_to_fit=True,
    font="STKaiti",
    font_size=14,
    font_color="blue",
    horizontal_alignment=utils.horizontal_alignments.left,
)
sf.apply_style_by_indexes(indexes_to_style=[0], styler_obj=first_line_style)

image.png

4.3. 背景色

再给第一行加一个红色背景(bg_color="red")。

first_line_style = Styler(
    shrink_to_fit=True,
    font="STKaiti",
    font_size=14,
    font_color="blue",
    bg_color="red",
    horizontal_alignment=utils.horizontal_alignments.left,
)
sf.apply_style_by_indexes(indexes_to_style=[0], styler_obj=first_line_style)

image.png

4.4. 边框

边框是区隔,突出内容的一种手段,比如,我们可以在表头部分用实线粗边框border_type=utils.borders.thick),内容部分用虚线细边框border_type=utils.borders.dashed)。

header_style = Styler(
    bg_color="yellow",
    bold=True,
    font_size=14,
    border_type=utils.borders.thick,
)
content_style = Styler(
    shrink_to_fit=True,
    font_size=12,
    border_type=utils.borders.dashed,
)

sf.apply_column_style(sf.columns, content_style)
sf.apply_headers_style(header_style)

image.png

4.5. 数字和日期

最后,看看如何定制数字(number_format)和日期(date_format)的显示方式。
我们把上面示例中的总价(totalPrice)保留两位小数,日期(DealDate)改为只显示月和日。

num_style = Styler(
    shrink_to_fit=True,
    font_size=12,
    number_format=utils.number_formats.general_float,
    border_type=utils.borders.dashed,
    horizontal_alignment=utils.horizontal_alignments.left,
)
sf.apply_column_style(["totalPrice", "unitPrice"], num_style)

date_style = Styler(
    shrink_to_fit=True,
    font_size=12,
    date_format="DD/MM",
    border_type=utils.borders.dashed,
    horizontal_alignment=utils.horizontal_alignments.left,
)
sf.apply_column_style("dealDate", date_style)

image.png

5. 总结

导出分析结果是我们做数据分析的最后一步,也是最容易被忽视的一步。
我们常常把大部分的精力都会花在数据的整理和分析上,最后给客户提供一个简易的报告和数据。

殊不知,导出一个美观清晰的分析结果和数据,反而更能得到客户的肯定和信任,因为这才是客户能够切身感知到的部分,否则花在数据整理和分析的精力再多,也不能让客户有直接的感受。

标签:Styler,style,utils,Excel,sf,horizontal,font,Pandas,美化
From: https://www.cnblogs.com/wang_yb/p/18070891

相关文章

  • 五.pandas常见操作
    目录五.pandas常见操作1.pandas处理字符串以上演示1-大小写转换2-去空格(两边).str.strip()3-切割4-连接.str.cat()5-空格检测.str.contains("")6-替换7-count()--返回元素出现次数8-repeat()2.查询操作2.1query("")2.2isin()2.3apply()3.缺失值处理......
  • 三.pandas基础
    目录一:认识pandas1.1pandas的优势1.2下载安装二:Series数据结构(一维)2.1创建Series创建series对象(一维)ndarray创建Series对象“显式索引”的方法定义索引标签dict创建Series对象(通过字典创建)标量创建Series对象2.2访问Series位置索引访问索引标签访问2.3......
  • Python-使用openpyxl读取excel内容
    1.本篇文章目标将下面的excel中的寄存器表单读入并构建一个字典2.openpyxl的各种基本使用方法2.1打开工作簿wb=openpyxl.load_workbook('test_workbook.xlsx')2.2获取工作簿中工作表名字并得到工作表ws=wb[wb.sheetnames[0]]wb.sheetnames会返回一个列表,列表中......
  • 上传文件附件时判断word、excel、txt等是否含有敏感词如身份证号,手机号等
    上传附件判断word、excel、txt等文档中是否含有敏感词如身份证号,手机号等,其它检测如PDF,图片(OCR)等可以自行扩展。互联网项目中,展示的数据中不能包含个人信息等敏感信息。判断word中是否包含手机号,word正文中是否包含身份证号等敏感信息,通过正则表达式判断匹配手机号,身份证号,以下做......
  • DBever导入越南文Excel
    HelloWorld有一个Excel文件中含有越南文1、将其另存为CSV,注意选择UTF-8格式的CSV。2、原文件的编码改成UTF-83、表映射中的目标字段的类型设置成nvarchar格式。......
  • python3实现xmind用例转excel
    1importxmindparser2importxlwt,xlrd3fromxlutils.copyimportcopy4fromxlwtimportWorksheet5fromxmindparserimportxmind_to_dict6importdatetime7importos8importre9importtraceback1011#当前时间戳12a=datetim......
  • pandas - 数据排序
    sort_values()函数importpandasaspddata={'名称':['太阳能','床','风扇','沙发'],'单价':[2000,3500,500,3500],'数量':[58,23,69,60]}df=pd.DataFrame(data)#单条件排序,使......
  • pandas - 删除数据
     importpandasaspddata={'名称':['太阳能','床','风扇'],'单价':[2000,3500,500],'数量':[58,23,69],'公司名称':'超市'}df=pd.DataFrame(data)df=df.renam......
  • 一文搞定POI,再也不怕excel导入导出了
    写在前面在Java日常开发过程中,实现Excel文件的导入导出功能是一项常见的需求。通过使用相关的Java库,如ApachePOI、EasyPoi或EasyExcel,可以轻松地实现Excel文件的读写操作。而这篇文章将介绍如何在Java中使用ApachePOI、EasyPoi和EasyExcel库来进行Excel文件的导入和导出操作......
  • pandas - 基础属性
    importpandasaspd#pd.set_option('display.unicode.east_asian_width',True)#规整格式#df=pd.read_excel(r'C:\Users\hui\Desktop\统计结果(1).xlsx')#new_df=df.T#print(df.dtypes)#查看属性#print(df.columns)#查看列索引#print(new_......