Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

python - single positional indexer is out-of-bounds : Error

I am practicing working in dataframe in pandas.i came across an error for which i dont understand the reason why there is an error.Can some one explain me the reason. Note: This only occurs when i use df.iloc[i+1,0] line of code. if i only use df.iloc[i,0] it works fine

Dataframe:

A,B
1,2
2,3
4,5
5,6
6,7
7,8
9,10

Code:

import pandas as pd
df = pd.read_csv("text.txt")
for i in range(0,len(df)):
    if (df.iloc[i,0] + df.iloc[i+1,0]) == 5 :
        print("hey")

Error: single positional indexer is out-of-bounds


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your program finds the current value and the next value in the column "A". However, once it reaches the end of the "A" column of the dataframe, there are no other values in the dataframe, but it still looks for the next value: .iloc[i + 1, 0], which doesn't exist. This leads to the error you were having. The issue can be solved by changing the range to 1 less than the length of the dataframe. That means the loop will stop one value before the end of the dataframe, read the final value, then exit.

import pandas as pd
df = pd.read_csv("test.txt")
for i in range(0,len(df)-1):
    if (df.iloc[i,0] + df.iloc[i+1,0]) == 5 :
        print("hey")


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...