Ask a simple code question about the dataFrame drop indexer is out-of-bounds

Asked 2 years ago, Updated 2 years ago, 37 views

mydict = [{'inx':'i','a': 1, 'b': 2, 'c': 3, 'd': 4},
          {'inx':'b','a': 100, 'b': 200, 'c': 300, 'd': 400},
          {'inx':'k','a': 1000, 'b': 2000, 'c': 3000, 'd': 4000 }]
df = pd.DataFrame(mydict)
df.set_index(['inx'],inplace=True)

for i in range(len(df)):
    if sum(df.iloc[i])<100:
        df.drop([df.iloc[i].name],inplace = True)
df

If I turn the code like this, the error below occurs... I don't know why

pandas python

2022-09-21 11:34

2 Answers

if sum(df.iloc[i])<100:

The error indexer is out-of-bounds occurs for this part. This means that i in iloc[i] exceeds the range.

In the for loop, a drop occurs and the len of the df changes, and as the for loop turns around the first len, the problem of the index passing occurs.


2022-09-21 11:34

My boss explained it well, so I changed the code.

mydict = [{'inx':'i','a': 1, 'b': 2, 'c': 3, 'd': 4},
          {'inx':'b','a': 100, 'b': 200, 'c': 300, 'd': 400},
          {'inx':'k','a': 1000, 'b': 2000, 'c': 3000, 'd': 4000 }]
df = pd.DataFrame(mydict)
df.set_index(['inx'],inplace=True)
df = df.loc[df.sum(axis=1) >= 100]

It's probably the same result as you want


2022-09-21 11:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.