GliterallyMyLife
GliterallyMyLife

Reputation: 11

iloc - IndexError("positional indexers are out-of-bounds") even though it's within the bounds

I'm trying to get the rows from specific indexes (these indexes are in a list). I keep getting an IndexError even though these indexes (ones in the list) are within the range

The df has an index count of 10872 (with the highest value being 2600) The list has a count of 628 (with the highest value being 2500)

list = df.loc[df[col] == value].index.tolist
df.iloc[[list]]

I want to print out the data then eventually get the next 4 rows from each of the specific indices

Upvotes: 1

Views: 11956

Answers (1)

BENY
BENY

Reputation: 323226

Here you should not using .iloc for index , .iloc is for the position and , loc is for the index

So in your case you should

l= df.loc[df[col] == value].index.tolist()

df.loc[l]

For example

df
Out[59]: 
  key
1   1
3   1
4   1
7   2
9   3

If you want to get the 1st row with .iloc you can

df.iloc[[0]]
Out[61]: 
  key
1   1

but with loc

df.loc[[1]]
Out[62]: 
  key
1   1

The error , when you want the last row , and the index is number 9 , but there is no position 9 for df.

df.iloc[9]
IndexError: single positional indexer is out-of-bounds
df.loc[9]
Out[64]: 
key    3
Name: 9, dtype: object

Upvotes: 3

Related Questions