VGB
VGB

Reputation: 497

what is the complimentary method of pd.DataFrame.drop()?

This is how I drop rows based on given index_value.

df_new = df.drop(df.index[index_value])

If I want to drop all the rows other than which is mentioned in index_value from dataframe df How to do it?

Index value is ind.ind1

ind

     ind1  ind2
0       0     2
1       1     6
2       2     8
3       3     9
4       4    14
df
     index     YearDeci  Year  Month  ...    Lon  Depth  Magnitude  Mag_Type
0     6131  2018.023393  2018      1  ...  76.16      5        2.9        ML
1     6132  2018.114803  2018      2  ...  77.22     10        2.5        MW
2     6133  2018.137808  2018      2  ...  75.82     10        3.2        ML
3     6134  2018.159566  2018      2  ...  78.68     10        3.1        ML
4     6135  2018.186685  2018      3  ...  76.67     10        4.0        MW

Upvotes: 1

Views: 81

Answers (3)

Vishnudev Krishnadas
Vishnudev Krishnadas

Reputation: 10960

Directly drop the desired index from the dataframe

df.drop(ind.ind1.to_list())

Upvotes: 1

Mayank Porwal
Mayank Porwal

Reputation: 34086

You can also use index.isin with ~:

df_new = df.drop(~df.index.isin([index_value]))

OR:

As @Ch3steR mentioned in the comment:

Just select the row with index you want:

df_new = df.loc[index_value]

Upvotes: 1

anky
anky

Reputation: 75100

Use index.difference:

df_new = df.drop(df.index.difference([index_value]))

Upvotes: 3

Related Questions