Pandas DataFrame Describe 方法

PythonPythonBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,你将学习如何使用 Pandas 库中的 describe() 方法为 DataFrame 生成描述性统计信息。describe() 方法会计算数值列的各种统计指标,如计数、均值、标准差、最小值、最大值和百分位数。它还会为包含对象数据类型的列提供摘要统计信息。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到 Notebook 标签页,以访问 Jupyter Notebook 进行练习。

有时,你可能需要等待几秒钟,直到 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,可以随时向 Labby 寻求帮助。实验结束后请提供反馈,我们将及时为你解决问题。

导入所需的库并创建 DataFrame

首先,使用 import 关键字导入 Pandas 库。然后使用 pd.DataFrame() 方法创建包含示例数据的 DataFrame。

import pandas as pd

## Create a DataFrame
df = pd.DataFrame([['Abhishek', 100, 'Science', 90],
                   ['Anurag', 101, 'Science', 85],
                   ['Chetan', 103, 'Maths', 75]],
                  columns=['Name', 'Roll No', 'Subject', 'Marks'])

使用 describe() 方法描述 DataFrame

要描述 DataFrame,可以在 DataFrame 对象上使用 describe() 方法。

## Describe the DataFrame
description = df.describe()

## Print the description
print(description)

描述 DataFrame 的所有列

要描述 DataFrame 的所有列,包括数值和对象数据类型,可以在 describe() 方法中使用 include='all' 参数。

## Describe all columns of the DataFrame
description_all_columns = df.describe(include='all')

## Print the description of all columns
print(description_all_columns)

描述 DataFrame 的特定列

要描述 DataFrame 的特定列,可以将其作为属性访问并使用 describe() 方法。

## Describe a specific column of the DataFrame
marks_description = df.Marks.describe()

## Print the description of the 'Marks' column
print(marks_description)

从描述中排除数值列

要从描述中排除数值列,可以在 describe() 方法中使用 exclude=np.number 参数。

import numpy as np

## Exclude numeric columns from the description
description_exclude_numeric = df.describe(exclude=np.number)

## Print the description excluding numeric columns
print(description_exclude_numeric)

描述包含 None 值的 DataFrame

要描述包含 None 值的 DataFrame,describe() 方法会适当地处理这些值。

## Create a DataFrame with None values
df_with_none = pd.DataFrame([['Abhishek', 101, 'Science', None],
                             ['Anurag', None, 'Science', 85],
                             ['Chetan', None, 'Maths', 75]],
                            columns=['Name', 'Roll No', 'Subject', 'Marks'])

## Describe the DataFrame with None values
description_with_none = df_with_none.describe()

## Print the description of the DataFrame with None values
print(description_with_none)

总结

恭喜!在这个实验中,你学习了如何使用 Pandas 中的 describe() 方法为 DataFrame 生成描述性统计信息。你可以使用此方法获取有关数据集分布的中心趋势、离散程度和形状的宝贵见解。describe() 方法是数据分析和探索的强大工具。祝你编程愉快!