如何使用索引访问 Pandas Series 元素?


Pandas Series 对象中的数据具有索引标签,这些索引标签用于访问或检索元素。每个索引值对应于系列中的一个元素。

索引主要分为两种类型:位置索引和标签索引。位置索引是指从 0 到 n-1(系列中存在的元素数量 n)的整数。而标签索引则是用户定义的标签,可以是任何东西,例如整数、对象、日期时间等等。

示例

# 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('
Accessing elements by using index values') # accessing elements by using index values print(series[[2,7]])

解释

以下示例将使用 NumPy.random 模型创建一个具有 10 个随机生成值的位置索引 Pandas Series 对象。

series[[2,7]] 将同时访问系列对象中地址为 2 和 7 的元素。如果要访问一个元素,我们可以这样表示:series[index_values]。

输出

0   0.517225
1   0.933815
2   0.183132
3   0.333059
4   0.993192
5   0.826969
6   0.761213
7   0.274025
8   0.129120
9   0.901257
dtype: float64

Accessing elements by using index values
2   0.183132
7   0.274025
dtype: float64

0.183132 和 0.274025 是系列对象中位置索引为 2、7 的值。

示例

如果我们有标签索引数据,并且想要访问系列元素,则可以指定这些标签索引地址来检索元素。

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

# creating pandas Series object
series = pd.Series({'black':'white', 'body':'soul', 'bread':'butter', 'first':'last'})
print(series)

print('
Accessing elements by using index labels') # accessing elements by using index values print(series['black'])

解释

最初,我们使用 Python 字典创建了一个带标签索引数据的 Series 对象,字典包含字符串类型的键和值,这些键充当我们的索引值。

在这个示例中,我们正在访问地址为“black”的元素,因此结果输出将在输出块中显示。

输出

black   white
body     soul
bread  butter
first    last
dtype: object

Accessing elements by using index labels
white

标签“black”的输出为“white”,同样,我们可以从系列中访问标签元素。上面输出的第一块是整个 Series 对象。

更新于: 2021年11月17日

1K+ 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.