Pandas系列中head()方法有什么用?

的head()在熊猫系列方法用于从一系列对象中检索最上面的行。默认情况下,它会显示5行系列数据,我们可以自定义5行以外的行数。

这个方法将一个整数值作为参数来返回一个包含这么多行的系列,假设如果你将整数 n 作为参数提供给 head 方法,head(n)那么它将返回一个包含 n 个元素的 Pandas 系列。这些元素是我们的熊猫系列对象的前 n 个元素。

示例

# importing required packages
import pandas as pd
import numpy as np

# creating pandas Series object
series = pd.Series(np.random.rand(20))

print(series)

print('\nThe Resultant series from head() method:')
# Displaying top row from series data
print(series.head())

解释

在此示例中,我们使用 NumPy 包创建了一个包含所有随机生成值的 Pandas 系列对象“系列”。

在这里,我们为“np.random.rand”方法定义了一个整数值 20,以获取 20 个随机值作为我们pandas.series函数的参数。因此,此系列对象中存在的元素总数为 20,索引标签是由熊猫系列函数自动生成的位置索引值。

输出结果

0   0.109458
1   0.199291
2   0.007854
3   0.205035
4   0.546315
5   0.442926
6   0.897214
7   0.950229
8   0.494563
9   0.843451
10  0.582327
11  0.257302
12  0.915850
13  0.364164
14  0.388809
15  0.918468
16  0.598981
17  0.631225
18  0.555009
19  0.684256
dtype: float64

The Resultant series from head() method:
0  0.109458
1  0.199291
2  0.007854
3  0.205035
4  0.546315
dtype: float64

上面的输出块有两个输出,一个是实际的熊猫系列对象“系列”,第二个是来自该head()方法显示的系列对象(系列)的顶部元素的输出。

示例

import pandas as pd

# creating dates
date = pd.date_range("2021-01-01", periods=15, freq="M")

# creating pandas Series with date index
S_obj = pd.Series(date, index=date.month_name())

print(S_obj)

print('\nThe Resultant series from head() method:')
# Displaying top row from series data
print(S_obj.head(1))

解释

在第一个例子中,我们已经看到了 head 方法的默认输出,它默认从系列对象中检索 5 个元素。我们可以通过向 head 函数发送一个整数参数来从 head 方法中获得所需数量的输出元素。

输出结果

January   2021-01-31
February  2021-02-28
March     2021-03-31
April     2021-04-30
May       2021-05-31
June      2021-06-30
July      2021-07-31
August    2021-08-31
September 2021-09-30
October   2021-10-31
November  2021-11-30
December  2021-12-31
January   2022-01-31
February  2022-02-28
March     2022-03-31
dtype: datetime64[ns]

The Resultant series from head() method:
January  2021-01-31
dtype: datetime64[ns]

在此示例中,我们将整数值 1 作为参数发送到 head 方法。我们可以在上面的输出块中看到结果,它返回一个元素,它是我们系列对象中最顶层的元素。