如何在 Pandas DataFrame 的 .iloc 属性中应用切片索引器?
Pandas DataFrame 的 .iloc 是一个属性,用于使用基于整数位置的索引值访问 DataFrame 的元素。
属性 .iloc 仅接受指定行和列索引位置的整数。通常,基于位置的索引值从 0 到 length-1。
超出此范围,我们才能访问 DataFrame 元素,否则会引发“IndexError”。但是,切片索引器不会对超出范围的索引值引发“IndexError”,因为它允许超出范围的索引值。
示例 1
在以下示例中,我们已将切片索引器应用于 iloc 属性以访问第 1 到第 3 行的值。此处,3 被排除在外。
# importing pandas package
import pandas as pd
# create a Pandas DataFrame
df = pd.DataFrame([['a','b'],['c','d'],['e','f'],['g','h']], columns=['col1','col2'])
print("DataFrame:")
print(df)
# Access the elements using slicing indexer
result = df.iloc[1:3]
print("Output:")
print(result)输出
输出如下所示:
DataFrame: col1 col2 0 a b 1 c d 2 e f 3 g h Output: col1 col2 1 c d 2 e f
iloc 属性通过向“.iloc”属性指定切片索引器对象,成功地从给定的 DataFrame 中访问了 2 行元素。
示例 2
现在,让我们将切片索引器与负边界值一起应用于 iloc 属性。
# importing pandas package
import pandas as pd
# create a Pandas DataFrame
df = pd.DataFrame([['a','b'],['c','d'],['e','f'],['g','h']], columns=['col1','col2'])
print("DataFrame:")
print(df)
# Apply slicing indexer with negative bound values
result = df.iloc[-4:-1]
print("Output:")
print(result)输出
输出如下所示:
DataFrame: col1 col2 0 a b 1 c d 2 e f 3 g h Output: col1 col2 0 a b 1 c d 2 e f
负边界值 [-4:-1] 被赋予 iloc 属性。然后它返回一个包含已访问元素的新 DataFrame。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP