活动公告

系统通知
05-18 21:22
系统通知
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,资源失效请在帖子内回复要求补档,会尽快处理!
10-23 09:31

pandas输出总是不如意掌握这些显示设置和格式化技巧让你的数据分析结果专业又美观

SunJu_FaceMall

3万

主题

2860

科技点

3万

积分

白金月票

碾压王

积分
32872

塔罗立华奏

<font color=白金月票" /> 发表于 2025-9-17 09:30:00 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
在数据分析工作中,我们经常使用pandas处理和展示数据,但默认的输出格式往往不够美观,甚至难以阅读。本文将详细介绍如何通过pandas的显示设置和格式化技巧,让你的数据分析结果既专业又美观。

1. 引言

Pandas是Python数据分析的核心库,但其默认显示设置常常无法满足我们的需求。数据可能被截断、数字显示不直观、表格样式单调等问题经常出现。通过掌握pandas的显示选项和格式化功能,我们可以轻松解决这些问题,使数据分析结果更加专业和易于理解。

2. Pandas显示选项基础

Pandas提供了pd.set_option()函数来控制数据的显示方式。我们先了解一些基本的显示选项:
  1. import pandas as pd
  2. import numpy as np
  3. # 创建一个示例DataFrame
  4. data = {
  5.     'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva', 'Frank', 'Grace', 'Henry', 'Ivy', 'Jack'],
  6.     'Age': [25, 30, 35, 40, 45, 50, 55, 60, 65, 70],
  7.     'Income': [50000.123456, 60000.234567, 70000.345678, 80000.456789, 90000.567890,
  8.                100000.678901, 110000.789012, 120000.890123, 130000.901234, 140000.012345],
  9.     'Description': ['This is a long description for Alice',
  10.                     'This is a long description for Bob',
  11.                     'This is a long description for Charlie',
  12.                     'This is a long description for David',
  13.                     'This is a long description for Eva',
  14.                     'This is a long description for Frank',
  15.                     'This is a long description for Grace',
  16.                     'This is a long description for Henry',
  17.                     'This is a long description for Ivy',
  18.                     'This is a long description for Jack']
  19. }
  20. df = pd.DataFrame(data)
  21. # 查看当前所有显示选项
  22. pd.describe_option()
复制代码

通过pd.describe_option()可以查看所有可用的显示选项,但输出会很长。我们通常只关心几个常用的选项。

3. 控制显示行列数

默认情况下,pandas可能会截断显示过多的行或列。我们可以通过以下设置来控制显示的行列数:
  1. # 设置最大显示行数
  2. pd.set_option('display.max_rows', 10)  # 显示最多10行
  3. pd.set_option('display.min_rows', 5)   # 至少显示5行
  4. # 设置最大显示列数
  5. pd.set_option('display.max_columns', 10)  # 显示最多10列
  6. # 显示所有行和列(谨慎使用,大数据集可能导致性能问题)
  7. pd.set_option('display.max_rows', None)
  8. pd.set_option('display.max_columns', None)
  9. # 恢复默认设置
  10. pd.reset_option('display.max_rows')
  11. pd.reset_option('display.max_columns')
  12. # 查看当前设置
  13. print(pd.get_option('display.max_rows'))
  14. print(pd.get_option('display.max_columns'))
复制代码

例如,如果我们有一个包含20行的DataFrame,默认可能只显示前5行和后5行:
  1. # 创建一个包含20行的DataFrame
  2. large_df = pd.DataFrame(np.random.rand(20, 4), columns=['A', 'B', 'C', 'D'])
  3. # 默认显示
  4. print(large_df)
复制代码

通过设置display.max_rows为20,我们可以显示所有行:
  1. pd.set_option('display.max_rows', 20)
  2. print(large_df)
复制代码

4. 调整列宽和精度

长文本或小数位数过多时,pandas的显示可能不够美观。我们可以调整列宽和数值精度:
  1. # 设置列宽
  2. pd.set_option('display.max_colwidth', 50)  # 每列最多显示50个字符
  3. # 设置浮点数精度
  4. pd.set_option('display.precision', 2)  # 浮点数显示2位小数
  5. # 设置浮点数格式
  6. pd.set_option('display.float_format', '{:.2f}'.format)  # 浮点数格式化为2位小数
  7. # 恢复默认设置
  8. pd.reset_option('display.max_colwidth')
  9. pd.reset_option('display.precision')
  10. pd.reset_option('display.float_format')
复制代码

让我们看看这些设置的效果:
  1. # 默认显示
  2. print("默认显示:")
  3. print(df[['Name', 'Description']].head())
  4. # 调整列宽后
  5. pd.set_option('display.max_colwidth', 30)
  6. print("\n调整列宽后:")
  7. print(df[['Name', 'Description']].head())
  8. # 调整浮点数精度后
  9. pd.set_option('display.precision', 4)
  10. print("\n调整浮点数精度后:")
  11. print(df[['Age', 'Income']].head())
  12. # 使用float_format格式化
  13. pd.set_option('display.float_format', '${:,.2f}'.format)
  14. print("\n使用float_format格式化后:")
  15. print(df[['Age', 'Income']].head())
  16. # 恢复默认设置
  17. pd.reset_option('display.max_colwidth')
  18. pd.reset_option('display.precision')
  19. pd.reset_option('display.float_format')
复制代码

5. 格式化数值显示

除了全局设置,我们还可以对特定列进行格式化,使数据显示更加专业:
  1. # 创建格式化函数
  2. def format_income(x):
  3.     return "${:,.2f}".format(x)
  4. def format_age(x):
  5.     return "{} years".format(x)
  6. # 使用apply方法应用格式化
  7. formatted_df = df.copy()
  8. formatted_df['Income'] = formatted_df['Income'].apply(format_income)
  9. formatted_df['Age'] = formatted_df['Age'].apply(format_age)
  10. print(formatted_df.head())
复制代码

使用style属性可以更灵活地格式化DataFrame:
  1. # 使用style格式化
  2. styled_df = df.style.format({
  3.     'Income': '${:,.2f}',
  4.     'Age': '{} years'
  5. })
  6. # 显示styled_df
  7. styled_df
复制代码

style对象还支持链式操作,可以添加更多格式化选项:
  1. # 链式格式化
  2. styled_df = df.style.format({
  3.     'Income': '${:,.2f}',
  4.     'Age': '{} years'
  5. }).hide_index()  # 隐藏索引
  6. styled_df
复制代码

6. 样式和条件格式化

Pandas的style属性不仅可以格式化数值,还可以添加样式和条件格式化,使数据更易于理解:
  1. # 创建一个数值型DataFrame用于演示
  2. numeric_df = pd.DataFrame(np.random.randn(10, 4), columns=['A', 'B', 'C', 'D'])
  3. # 1. 高亮最大值
  4. styled_max = numeric_df.style.highlight_max(axis=0)
  5. styled_max
  6. # 2. 高亮最小值
  7. styled_min = numeric_df.style.highlight_min(axis=0)
  8. styled_min
  9. # 3. 高亮空值
  10. df_with_na = numeric_df.copy()
  11. df_with_na.iloc[2, 1] = np.nan
  12. df_with_na.iloc[5, 3] = np.nan
  13. styled_na = df_with_na.style.highlight_null(null_color='red')
  14. styled_na
  15. # 4. 渐变色背景
  16. styled_bg = numeric_df.style.background_gradient(cmap='Blues')
  17. styled_bg
  18. # 5. 条件格式化
  19. def color_negative_red(val):
  20.     color = 'red' if val < 0 else 'black'
  21.     return f'color: {color}'
  22. styled_conditional = numeric_df.style.applymap(color_negative_red)
  23. styled_conditional
复制代码

我们还可以组合多种样式:
  1. # 组合样式
  2. combined_style = numeric_df.style.format('{:.2f}') \
  3.     .background_gradient(cmap='Blues') \
  4.     .highlight_max(axis=0, color='red') \
  5.     .highlight_min(axis=0, color='green') \
  6.     .hide_index()
  7. combined_style
复制代码

7. 导出格式化结果

格式化后的DataFrame可以导出为多种格式,方便在报告或演示中使用:
  1. # 1. 导出为HTML
  2. html = styled_df.render()
  3. with open('styled_table.html', 'w') as f:
  4.     f.write(html)
  5. # 2. 导出为Excel
  6. styled_df.to_excel('styled_table.xlsx', engine='openpyxl')
  7. # 3. 导出为LaTeX
  8. latex = styled_df.to_latex()
  9. print(latex)
  10. # 4. 使用DataFrame的to_html方法
  11. html_simple = df.to_html(classes='table table-striped')
  12. with open('simple_table.html', 'w') as f:
  13.     f.write(html_simple)
复制代码

8. 高级显示技巧

8.1 使用IPython.display进行更丰富的显示

在Jupyter Notebook中,我们可以使用IPython.display模块来增强显示效果:
  1. from IPython.display import display, HTML
  2. # 创建一个包含HTML标签的DataFrame
  3. html_df = df.copy()
  4. html_df['Name'] = html_df['Name'].apply(lambda x: f'<b>{x}</b>')
  5. html_df['Income'] = html_df['Income'].apply(lambda x: f'<span style="color: green">${x:,.2f}</span>')
  6. # 使用HTML显示
  7. display(HTML(html_df.to_html(escape=False)))
复制代码

8.2 创建自定义样式函数

我们可以创建自定义样式函数,实现更复杂的格式化需求:
  1. def style_by_income(val):
  2.     if val > 100000:
  3.         return 'background-color: lightgreen'
  4.     elif val > 70000:
  5.         return 'background-color: yellow'
  6.     else:
  7.         return 'background-color: lightcoral'
  8. def style_by_age(val):
  9.     if val > 60:
  10.         return 'color: red; font-weight: bold'
  11.     elif val > 40:
  12.         return 'color: blue'
  13.     else:
  14.         return 'color: black'
  15. # 应用自定义样式
  16. custom_styled = df.style.applymap(style_by_income, subset=['Income']) \
  17.                    .applymap(style_by_age, subset=['Age']) \
  18.                    .format({'Income': '${:,.2f}'}) \
  19.                    .set_caption('Employee Data') \
  20.                    .set_properties(**{'text-align': 'center'})
  21. custom_styled
复制代码

8.3 使用表格样式

我们可以为整个表格设置样式:
  1. # 设置表格样式
  2. table_style = [{
  3.     'selector': 'caption',
  4.     'props': [
  5.         ('color', 'darkblue'),
  6.         ('font-size', '16px'),
  7.         ('font-weight', 'bold')
  8.     ]
  9. }, {
  10.     'selector': 'th',
  11.     'props': [
  12.         ('background-color', '#f7f7f9'),
  13.         ('color', '#333'),
  14.         ('font-weight', 'bold'),
  15.         ('border', '1px solid #ddd')
  16.     ]
  17. }, {
  18.     'selector': 'td',
  19.     'props': [
  20.         ('border', '1px solid #ddd'),
  21.         ('text-align', 'center')
  22.     ]
  23. }]
  24. # 应用表格样式
  25. table_styled = df.style.set_table_styles(table_style) \
  26.                       .format({'Income': '${:,.2f}'}) \
  27.                       .set_caption('Employee Information')
  28. table_styled
复制代码

8.4 使用条形图可视化数值

我们可以在DataFrame中直接添加条形图,使数值更直观:
  1. # 添加条形图
  2. bar_styled = df.style.format({'Income': '${:,.2f}'}) \
  3.                 .bar(subset=['Income'], color='#5fba7d') \
  4.                 .bar(subset=['Age'], color='#ff9f43', vmin=0, vmax=100)
  5. bar_styled
复制代码

9. 总结

通过本文介绍的各种pandas显示设置和格式化技巧,你可以轻松地将数据分析结果变得更加专业和美观。以下是一些关键点的总结:

1. 全局显示选项:使用pd.set_option()可以控制pandas的全局显示行为,如最大行列数、列宽、数值精度等。
2. 数值格式化:通过style.format()方法可以灵活地格式化数值,如添加货币符号、百分比、单位等。
3. 条件格式化:使用highlight_max()、highlight_min()、background_gradient()等方法可以突出显示重要数据。
4. 自定义样式:通过自定义样式函数,可以实现更复杂的格式化需求,如根据数值范围设置不同颜色。
5. 导出格式化结果:格式化后的DataFrame可以导出为HTML、Excel、LaTeX等多种格式,方便在报告或演示中使用。
6. 高级显示技巧:结合IPython.display、自定义样式函数、表格样式和条形图等技巧,可以创建更加丰富和直观的数据展示。

全局显示选项:使用pd.set_option()可以控制pandas的全局显示行为,如最大行列数、列宽、数值精度等。

数值格式化:通过style.format()方法可以灵活地格式化数值,如添加货币符号、百分比、单位等。

条件格式化:使用highlight_max()、highlight_min()、background_gradient()等方法可以突出显示重要数据。

自定义样式:通过自定义样式函数,可以实现更复杂的格式化需求,如根据数值范围设置不同颜色。

导出格式化结果:格式化后的DataFrame可以导出为HTML、Excel、LaTeX等多种格式,方便在报告或演示中使用。

高级显示技巧:结合IPython.display、自定义样式函数、表格样式和条形图等技巧,可以创建更加丰富和直观的数据展示。

掌握这些技巧后,你的数据分析结果将不再只是枯燥的数字,而是能够清晰传达信息、吸引注意力的专业展示。无论是在数据分析报告、学术论文还是商业演示中,这些格式化技巧都能帮助你更好地展示数据洞察。
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则