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 !
df= df[df.index < 13492]
works for this case
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With