访问 Pandas Series 的元素


Pandas Series 是一个一维带标签的数组,可以保存任何类型的数据(整数、字符串、浮点数、Python 对象等)。可以使用多种方法访问 Pandas Series 的元素。

让我们先创建一个 Pandas Series,然后访问它的元素。

创建 Pandas Series

Pandas Series 的创建可以通过多种形式的数据来实现,例如 ndarray、列表、常量以及索引值,索引值必须唯一且可哈希。下面是一个例子。

示例

import pandas as pd
s = pd.Series([11,8,6,14,25],index = ['a','b','c','d','e'])
print s

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

运行以上代码将得到以下结果:

a    11
b    8
c    6
d    14
e  25
dtype: int64

访问 Series 的元素

我们可以使用多种方法访问 Series 的数据元素。我们将继续使用上面创建的 Series 来演示各种访问方法。

访问第一个元素

第一个元素位于索引 0 位置。因此,可以通过在 Series 中提及索引值来访问它。我们可以使用 0 或自定义索引来获取值。

示例

import pandas as pd
s = pd.Series([11,8,6,14,25],index = ['a','b','c','d','e'])
print s[0]
print s['a']

输出

运行以上代码将得到以下结果:

11
11

访问前三个元素

与上述类似,我们可以使用索引值 3 之前的冒号值或相应的自定义索引值来获取前三个元素。

示例

import pandas as pd
s = pd.Series([11,8,6,14,25],index = ['a','b','c','d','e'])
print s[:3]
print s[:'c']

输出

运行以上代码将得到以下结果:

a    11
b    8
c    6
dtype: int64
a    11
b   8
c 6
dtype: int64

访问最后三个元素

与上述类似,我们可以使用索引值 3 结尾的冒号值和负号或相应的自定义索引值来获取最后三个元素。

示例

import pandas as pd
s = pd.Series([11,8,6,14,25],index = ['a','b','c','d','e'])
print s[-3:]
print s['c':]

输出

运行以上代码将得到以下结果:

c 6
d 14
e 25
dtype: int64
c 6
d 14
e 25
dtype: int64

使用索引标签访问元素

在这种情况下,我们使用自定义索引值来访问 Series 的非连续元素。

示例

import pandas as pd
s = pd.Series([11,8,6,14,25],index = ['a','b','c','d','e'])
print s[['c','b','e']]

输出

运行以上代码将得到以下结果:

c 6
b 8
e 25
dtype: int64

更新于:2020年6月30日

10K+ 浏览量

启动你的职业生涯

通过完成课程获得认证

开始学习
广告