Pandas - 分析 DataFrame
查看数据
要快速了解 DataFrame,最常用的方法是 head()
方法。
head()
方法会返回列标题和从顶部开始的指定行数。
示例
通过打印 DataFrame 的前 10 行来快速了解
import pandas as pd
df = pd.read_csv('data.csv')
print(df.head(10))
自己动手试一试 »
在我们的示例中,我们将使用一个名为 'data.csv' 的 CSV 文件。
下载 data.csv,或在浏览器中打开 data.csv。
注意:如果未指定行数,head()
方法将返回前 5 行。
还有一个 tail()
方法,用于查看 DataFrame 的最后几行。
tail()
方法会返回列标题和从底部开始的指定行数。
数据信息
DataFrame 对象有一个名为 info()
的方法,该方法可以提供有关数据集的更多信息。
示例
打印数据信息
print(df.info())
结果
<class 'pandas.core.frame.DataFrame'> RangeIndex: 169 entries, 0 to 168 Data columns (total 4 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Duration 169 non-null int64 1 Pulse 169 non-null int64 2 Maxpulse 169 non-null int64 3 Calories 164 non-null float64 dtypes: float64(1), int64(3) memory usage: 5.4 KB None
结果解释
结果告诉我们有 169 行和 4 列
RangeIndex: 169 entries, 0 to 168 Data columns (total 4 columns):
以及每一列的名称及其数据类型
# Column Non-Null Count Dtype --- ------ -------------- ----- 0 Duration 169 non-null int64 1 Pulse 169 non-null int64 2 Maxpulse 169 non-null int64 3 Calories 164 non-null float64
空值
info()
方法还告诉我们每一列存在多少个非空值,在我们的数据集中,"Calories" 列有 164 个非空值,总共 169 行。
这意味着,无论出于何种原因,"Calories" 列中有 5 行完全没有值。
空值或 Null 值在分析数据时可能很糟糕,您应该考虑删除包含空值的行。这是所谓的数据清理的一部分,您将在接下来的章节中学习更多关于这方面的内容。