How to drop rows based on column values using Pandas Dataframe

When you are working with data, sometimes you may need to remove the rows based on some column values.

Using pandas, you may follow the below simple code to achieve it.

Step 1 : Filter the rows which equals to the given value and store the indexes

Step 2 : Delete the rows related to the indexes

Delete rows based on multiple column values

Sometimes it may require you to delete the rows based on matching values of multiple columns. You may use below approach which is a extension of the same method which we discussed above.

# Get indexes where name column has value john and # value column equals to 0.0indexNames = df[(df[‘name’] == ‘john’) & (df[‘value’] == 0.0)].index# Delete these row indexes from dataFramedf.drop(indexNames , inplace=True)

Delete rows based on inverse of column values

Sometimes you need to drop the all rows which aren?t equal to a value given for a column. Pandas offer negation (~) operation to perform this feature.

# Get indexes where name column doesn’t have value johnindexNames = df[~(df[‘name’] == ‘john’)].index # Delete these row indexes from dataFramedf.drop(indexNames , inplace=True)

Done!

1

No Responses

Write a response