如何使用 .iloc 属性访问 pandas DataFrame 元素?
pandas.DataFrame.iloc 属性用于使用整数位置访问 pandas DataFrame 中的元素。它与 pandas.DataFrame 的“iat”属性非常相似,但区别在于,“iloc”属性可以访问一组元素,而“iat”属性只能访问单个元素。
“.iloc”属性允许使用整数、整数列表、包含整数的切片对象和布尔数组等作为输入。
如果请求的索引超出范围,该属性将引发“IndexError”异常,切片索引器对象除外。
示例 1
在下面的示例中,我们使用嵌套列表和整数值创建了一个 pandas DataFrame。之后,我们使用单个整数值应用了 iloc 属性。
# importing pandas package
import pandas as pd
# create a Pandas DataFrame
df = pd.DataFrame([[1,2,3,4],[10,20,30,40],[100,200,300,400]], columns=list('abcd'))
print("DataFrame:")
print(df)
# Access the elements using iloc attribute
result = df.iloc[0]
print("Output:")
print(result)输出
输出如下:
DataFrame: a b c d 0 1 2 3 4 1 10 20 30 40 2 100 200 300 400 Output: a 1 b 2 c 3 d 4 Name: 0, dtype: int64
iloc 属性访问了给定 DataFrame 中的整个第 0 行。
示例 2
让我们通过向 iloc 属性提供整数列表来访问 pandas.DataFrame 中的元素。在这个示例中,我们向“iloc”属性指定了 [0,1]。
# importing pandas package
import pandas as pd
# create a Pandas DataFrame
df = pd.DataFrame([[1,2,3,4],[10,20,30,40],[100,200,300,400]], columns=list('abcd'))
print("DataFrame:")
print(df)
# Access the elements using a list of integers
result = df.iloc[[0,1]]
print("Output:")
print(result)输出
输出如下:
DataFrame: a b c d 0 1 2 3 4 1 10 20 30 40 2 100 200 300 400 Output: a b c d 0 1 2 3 4 1 10 20 30 40
我们已成功使用“iloc”属性访问了 pandas DataFrame 中的第 0 行和第 1 行元素。结果,它返回一个新的 DataFrame 对象,如上面的输出块中所示。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP