Pandas 分析 DataFrames
查看数据
获取 DataFrame 快速概览最常用的方法之一是使用 head()
方法。
head()
方法从顶部开始返回表头和指定数量的行。
实例
通过打印 DataFrame 的前 10 行来快速概览:
import pandas as pd df = pd.read_csv('data.csv') print(df.head(10))
在我们的例子中,我们将使用一个名为 'data.csv' 的 CSV 文件。
注意:如果未指定行数,head()
方法将返回前 5 行。
实例
打印 DataFrame 的前 5 行:
import pandas as pd df = pd.read_csv('data.csv') print(df.head())
还有一个 tail()
方法用于查看 DataFrame 的最后几行。
tail()
方法从底部开始返回表头和指定数量的行。
实例
打印 DataFrame 的最后 5 行:
print(df.tail())
有关数据的信息
DataFrames 对象有一个名为 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 个非空值。
这意味着出于某种原因,"Calories" 列中有 5 行完全没有值。
在分析数据时,空值或 Null 值可能是有害的,您应该考虑删除具有空值的行。这是迈向所谓数据清洗的一步,您将在接下来的章节中了解更多信息。