Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove dataframe rows if index larger than x

Tags:

python

pandas

I want to remove dataframe rows that index is larger than 13491.

I tried

df.drop(df.index > [13491])

but received error

KeyError: 'labels [False False False ...  True  True  True] not contained in axis'

This one works fine

df= df[df.index < 13492]

But how to remove the filtered rows from dataframe ?

Can someone give me some suggestions ? Thank you in advanced !

like image 799
Osca Avatar asked Oct 24 '25 16:10

Osca


2 Answers

df= df[df.index < 13492] 

works for this case

like image 165
Osca Avatar answered Oct 26 '25 05:10

Osca


If you really want to use drop, you could identify the row with the help of numpy.where()

import pandas as pd
import numpy as np

df = pd.DataFrame()

df["A"] = [1,2,3,4,5]
   A
0  1
1  2
2  3
3  4

#Remove if index bigger thans 2
df.drop(df.index[np.where(df.index > 2)[0]])
   A
0  1
1  2
2  3

But your method of giving back df = df[df.index < some_value] should not be bad either. Keep in mind that drop will return a changed object and not overwrite the old one. so a df = df.drop ... is needed to replace df either way.

like image 40
philbox2 Avatar answered Oct 26 '25 06:10

philbox2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!