首页 文章资讯内容详情

如何从 Pandas 的系列中获取几行?

2026-06-02 1 花语

pandasSeries中的索引用于访问系列中的元素,同样,我们也可以使用切片技术从系列对象中获取一组值。我们只能从熊猫系列对象中检索子集。这个过程类似于NumPy数组切片。

可以通过定义系列的开始和结束索引值来检索某些元素集。

示例

# 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(\nRetrieve first 3 elements) # accessing elements by using index values print(series[0:3]) print(\nRetrieve 3 elements from middle) # accessing elements by using index values print(series[4:7])

解释

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

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

输出结果

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输出结果

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

示例

我们也可以切片标签索引系列对象,下面的例子将解释如何切片具有标签索引的系列。

# 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(\nRetrieve first 2 elements) # accessing elements by using index values print(series[0:2]) print(\nRetrieve elements by using label index) # accessing elements by using label index print(series[W:G])

解释

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

通过指定从0到2(series[0:2])的位置索引来访问系列中的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

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