如何在Pandas中使用describe()函数(带示例)

210 阅读2分钟

你可以使用**describe()**函数为pandas DataFrame生成描述性统计数据。

这个函数使用以下基本语法。

df.describe()

下面的例子展示了如何在实践中使用这个语法,并使用以下pandas DataFrame。

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'],
                   'points': [25, 12, 15, 14, 19, 23, 25, 29],
                   'assists': [5, 7, 7, 9, 12, 9, 9, 4],
                   'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})

#view DataFrame
df

	team	points	assists	rebounds
0	A	25	5	11
1	A	12	7	8
2	B	15	7	10
3	B	14	9	6
4	B	19	12	6
5	C	23	9	5
6	C	25	9	9
7	C	29	4	12

例1:描述所有的数字列

默认情况下,**describe()**函数只为pandas DataFrame中的数字列生成描述性统计。

#generate descriptive statistics for all numeric columns
df.describe()

	points	        assists	   rebounds
count	8.000000	8.00000	   8.000000
mean	20.250000	7.75000	   8.375000
std	6.158618	2.54951	   2.559994
min	12.000000	4.00000	   5.000000
25%	14.750000	6.50000	   6.000000
50%	21.000000	8.00000	   8.500000
75%	25.000000	9.00000	   10.250000
max	29.000000	12.00000   12.000000

描述性统计数据显示的是DataFrame中的三个数字列。

**注意:**如果任何列中有缺失的数值,pandas在计算描述性统计的时候会自动排除这些数值。

例2:描述所有的列

要计算DataFrame中每一列的描述性统计,我们可以使用include='all'参数。

#generate descriptive statistics for all columns
df.describe(include='all')

	team	points	    assists	rebounds
count	8	8.000000    8.00000	8.000000
unique	3	NaN	    NaN	        NaN
top	B	NaN	    NaN	        NaN
freq	3	NaN	    NaN	        NaN
mean	NaN	20.250000   7.75000	8.375000
std	NaN	6.158618    2.54951	2.559994
min	NaN	12.000000   4.00000	5.000000
25%	NaN	14.750000   6.50000	6.000000
50%	NaN	21.000000   8.00000	8.500000
75%	NaN	25.000000   9.00000	10.250000
max	NaN	29.000000   12.00000	12.000000

例3:描述特定列

下面的代码展示了如何计算pandas DataFrame中一个特定列的描述性统计。

#calculate descriptive statistics for 'points' column only
df['points'].describe()

count     8.000000
mean     20.250000
std       6.158618
min      12.000000
25%      14.750000
50%      21.000000
75%      25.000000
max      29.000000
Name: points, dtype: float64

下面的代码展示了如何计算几个特定列的描述性统计。

#calculate descriptive statistics for 'points' and 'assists' columns only
df[['points', 'assists']].describe()

	points	assists
count	8.000000	8.00000
mean	20.250000	7.75000
std	6.158618	2.54951
min	12.000000	4.00000
25%	14.750000	6.50000
50%	21.000000	8.00000
75%	25.000000	9.00000
max	29.000000	12.00000

你可以在这里找到**describe()**函数的完整文档。

其他资源

下面的教程解释了如何在pandas中执行其他常用函数。

Pandas:如何查找列中的唯一值
Pandas:如何查找两行之间的差值
Pandas:如何计算DataFrame中的缺失值

The postHow to Use describe() Function in Pandas (With Examples)appeared first onStatology.