文章目录
前言
在 Pandas 中,describe()
函数能够为数据框(DataFrame)中的数值列提供统计摘要信息。
一、describe()
函数是什么?
describe()
函数是 Pandas 数据框(DataFrame)对象的一个方法,它用于生成有关数据的统计摘要。这个统计摘要包括了数据列的数量、均值、标准差、最小值、25% 分位数、中位数(50% 分位数)、75% 分位数和最大值。
二、describe()
函数的基本用法
import pandas as pd
# 创建一个示例数据框
data = {'Age': [25, 30, 35, 40, 45],
'Salary': [50000, 60000, 75000, 80000, 90000]}
df = pd.DataFrame(data)
# 使用 describe() 函数生成统计摘要
summary = df.describe()
print(summary)
Age Salary
count 5.000000 5.000000
mean 35.000000 71000.000000
std 7.905694 15968.719423
min 25.000000 50000.000000
25% 30.000000 60000.000000
50% 35.000000 75000.000000
75% 40.000000 80000.000000
max 45.000000 90000.000000
三、describe()
函数的参数说明
describe()
函数有一些可选参数,可以用来控制统计摘要的输出。
percentiles
:指定要计算的百分位数,默认是[0.25, 0.5, 0.75]
,即 25%、50% 和 75% 分位数。include
和exclude
:用于选择要包含或排除的数据类型,默认情况下包括所有数值列。datetime_is_numeric
:如果为 True,则将日期时间列视为数值列进行统计。
四、示例代码
1. 使用 percentiles
参数
设置 percentiles
参数来自定义要计算的百分位数。例如:
custom_percentiles = [0.1, 0.5, 0.9]
custom_summary = df.describe(percentiles=custom_percentiles)
print(custom_summary)
2. 使用 include
和 exclude
参数
使用 include
和 exclude
参数来选择要包含或排除的数据类型。
integer_summary = df.describe(include='int')
print(integer_summary)
3. 处理日期时间列
如果数据框中包含日期时间列,使用 datetime_is_numeric
参数将其视为数值列进行统计。例如:
import datetime
dates = [datetime.date(2022, 1, 1), datetime.date(2022, 1, 2), datetime.date(2022, 1, 3)]
df['Date'] = dates
date_summary = df.describe(datetime_is_numeric=True)
print(date_summary)