如何使用Pandas head()函数(附示例)

1,557 阅读2分钟

你可以使用**head()**函数来查看 pandas DataFrame 的前_n_行。

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

df.head()

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

import pandas as pd

#create DataFrame
df = pd.DataFrame({'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

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

例1:查看DataFrame的前5行

默认情况下,**head()**函数会显示一个DataFrame的前5行。

#view first five rows of DataFrame
df.head()

	points	assists	rebounds
0	25	5	11
1	12	7	8
2	15	7	10
3	14	9	6
4	19	12	6

例2:查看DataFrame的前_n_行

我们可以使用n参数来查看一个pandas DataFrame的前_n_行。

#view first three rows of DataFrame
df.head(n=3)

        points	assists	rebounds
0	25	5	11
1	12	7	8
2	15	7	10

例3:查看特定列的前_n_行

下面的代码显示了如何查看DataFrame中某一列的前五行。

#view first five rows of values in 'points' column
df['points'].head()

0    25
1    12
2    15
3    14
4    19
Name: points, dtype: int64

例4:查看几列的前_n_行

下面的代码显示了如何在一个DataFrame中查看几个特定列的前五行。

#view first five rows of values in 'points' and 'assists' columns
df[['points', 'assists']].head()

	points	assists
0	25	5
1	12	7
2	15	7
3	14	9
4	19	12

其他资源

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

如何在Pandas中选择唯一的行
如何在Pandas数据框中洗刷行
如何在Pandas中获取列与值匹配的行的索引

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