pandasDataFrame.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