如何使用 .iloc 属性访问 Pandas Series 元素?


pandas.Series.iloc 属性用于访问基于整数位置索引的 Pandas Series 对象中的元素。它与 pandas.Series 的“iat”属性非常相似,但区别在于,“iloc”属性可以访问一组元素,而“iat”属性只能访问单个元素。

“.iloc”属性允许使用整数、整数列表和整数切片对象等作为输入值。

示例 1

import pandas as pd
import numpy as np

# create a pandas series
s = pd.Series([1,2,3,4,5,6,7,8,9,10])

print(s)

print("Output: ")
print(s.iloc[2])

解释

在下面的示例中,我们使用 Python 整数列表创建了一个 Pandas Series 对象“s”,并且我们没有初始化索引标签,因此 Pandas.Series 构造函数将根据提供给 Pandas.Series 构造函数的数据提供一系列索引值。

对于此示例,基于整数的位置索引从 0 到 9 开始。

输出

0  1
1  2
2  3
3  4
4  5
5  6
6  7
7  8
8  9
9  10
dtype: int64

Output: 3

我们通过向“iloc”属性提供基于整数的索引值来访问 Pandas.Series 对象中的单个元素。

示例 2

import pandas as pd
import numpy as np

# create a series
s = pd.Series([1,2,3,4,5,6,7,8,9,10])

print(s)

# access number of elements by using a list of integers
print("Output: ")
print(s.iloc[[1,4,5]])

解释

让我们通过提供表示给定序列的基于整数的索引位置的整数列表来访问 Pandas.Series 对象中的一组元素。

在此示例中,我们向“iloc”属性提供了整数列表 [1,4,5]。

输出

0  1
1  2
2  3
3  4
4  5
5  6
6  7
7  8
8  9
9  10
dtype: int64
Output:
1  2
4  5
5  6
dtype: int64

我们已成功使用“iloc”属性访问了一组 Pandas.Series 元素。结果,它返回另一个在上面输出块中显示的 Series 对象。

更新于: 2022-03-09

307 次查看

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.