如何在 Pandas 中获取 Series 的几行数据?


Pandas 中的 Series 的索引用于访问 Series 中的元素,同样,我们也可以使用**切片**技术从 Series 对象中获取一组值。换句话说,我们可以从 Pandas Series 对象中检索子集。此过程类似于 NumPy 数组切片。

可以通过定义 Series 的起始和终点索引值来检索一些元素集。

示例

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

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

print(series)

print('
Retrieve first 3 elements') # accessing elements by using index values print(series[0:3]) print('
Retrieve 3 elements from middle') # accessing elements by using index values print(series[4:7])

解释

在这个例子中,我们创建了一个带有位置索引值的 Series 对象,数据是使用 NumPy 随机模块生成的随机值。

在这里,我们通过定义起始和结束值(使用 Series 名称“series[start:end]”)从 Series 对象中检索了一组行。

输出

0   0.445380
1   0.644535
2   0.961340
3   0.242597
4   0.272414
5   0.126234
6   0.579381
7   0.358938
8   0.542832
9   0.476023
dtype: float64

Retrieve first 3 elements
0   0.445380
1   0.644535
2   0.961340
dtype: float64

Retrieve 3 elements from middle
4   0.272414
5   0.126234
6   0.579381
dtype: float64

输出

上面代码块的第一部分表示整个 Series 对象,第二部分是通过定义从 0 到 3 的索引范围(series[0:3])切片的子集值,同样,我们通过定义 4 到 7 之间的索引范围(series[4:7])检索了另一个子集,它在上面代码块的最后部分表示。

示例

我们还可以切片标签索引的 Series 对象,下面的示例将解释如何切片具有标签索引的 Series。

# importing required packages
import pandas as pd

# creating pandas Series object
series = pd.Series({'B':'black', 'W':'white','R':'red', 'Bl':'blue','G':'green'})
print(series)

print('
Retrieve first 2 elements') # accessing elements by using index values print(series[0:2]) print('
Retrieve elements by using label index') # accessing elements by using label index print(series['W':'G'])

解释

在上面的示例中,我们创建了一个带有标签索引的 Series 对象,并且我们使用了位置索引值以及标签索引值应用了切片。

通过指定从 0 到 2 的位置索引(series[0:2])访问了 Series 中的 2 个元素。同样,我们也指定了标签索引(例如 series[‘W’:’G’])。

输出

B   black
W   white
R     red
Bl   blue
G   green
dtype: object

Retrieve first 2 elements
B   black
W   white
dtype: object

Retrieve elements by using label index
W   white
R     red
Bl   blue
G   green
dtype: object

上面代码块是整个 Series 对象的输出,以及通过在标签索引 Series 对象上使用位置索引和标签索引访问的一些行。

更新于: 2021-11-17

136 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.