如何漂亮地打印整个Pandas系列或数据框架
在这篇文章中,我们将看到如何漂亮地打印整个pandas系列/数据框架。在这个方法中,有各种漂亮的打印选项可供使用。这里我们将讨论3种方法来漂亮地打印整个Pandas数据框架。
- 使用pd.set_options()方法
- 使用pd.option_context()方法
- 使用options.display()方法
创建DataFrame以漂亮地打印整个Pandas数据框架。
import pandas as pd
# Create a dataframe
df = pd.DataFrame({
'Product_id': ['ABC', 'DEF', 'GHI', 'JKL',
'MNO', 'PQR', 'STU', 'VWX'],
'Stall_no': [37, 38, 9, 50, 7, 23, 33, 4],
'Grade': [1, 0, 0, 2, 0, 1, 3, 0],
'Category': ['Fashion', 'Education', 'Technology',
'Fashion', 'Education', 'Technology',
'Fashion', 'Education'],
'Demand': [10, 12, 14, 15, 13, 20, 10, 15],
'charges1': [376, 397, 250, 144, 211, 633, 263, 104],
'charges2': [11, 12, 9, 13, 4, 6, 13, 15],
'Max_Price': [4713, 10352, 7309, 20814, 9261,
6104, 5257, 5921],
'Selling_price': [4185.9477, 9271.490256, 6785.701362,
13028.91782, 906.553935, 5631.247872,
3874.264992, 4820.943]})
display(df)
输出:
下面将讨论在漂亮的打印选项中使用的一些重要术语。
- display.max_columns:pandas应该打印的最大列数。如果提供了None作为参数,则打印所有列。
- display.max_rows :pandas应该打印的最大行数。如果提供了None作为参数,则打印所有的行。
- display.colheader_justify : 控制列标题的对齐。
- display.precision :以小数点后的位数为单位的浮点输出精度,用于常规格式化以及科学符号。
- display.width : 显示器的宽度,以字符为单位。如果设置为None,pandas将正确地自动检测宽度。
使用pd.set_options()减少Pandas数据框架的大小
我们将使用上述df的set_options()方法的一些选项来查看所有行、所有列、一行中的所有列以及居中对齐的列头,并将每个浮动值的小数点后的位数取整为2。
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 1000)
pd.set_option('display.colheader_justify', 'center')
pd.set_option('display.precision', 2)
display(df)
输出:
一旦通过pd.set_options()方法进行了设置,同样的设置将用于接下来的所有Dataframe打印命令。
使用pd.option_context()减少Pandas数据框架的大小
pd.set_option()方法为显示数据框架提供永久设置。 pd.option_context()在语句上下文中临时设置选项。下面的代码打印了上述4行的df,所有的列,所有的列在一行中,列头左对齐,并对每个浮动值的小数点后的位数进行了舍入。
with pd.option_context('display.max_rows', 5,
'display.max_columns', None,
'display.width', 1000,
'display.precision', 3,
'display.colheader_justify', 'left'):
display(df)
输出:
使用options.display减少Pandas数据框架的大小
以下代码打印了上述4行4列的df,所有列都在一行中,列头左对齐,并且不对每个浮动值的小数后的位数进行四舍五入。
import pandas as pd
import numpy as np
def display_options():
display = pd.options.display
display.max_columns = 5
display.max_rows = 4
display.max_colwidth = 222
display.width = None
return None
display_options()
display(df)
输出: