Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop rows on multiple conditions in pandas dataframe

Tags:

My df has 3 columns

df = pd.DataFrame({"col_1": (0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0), 
                   "col_2": (0.0, 0.24, 1.0, 0.0, 0.22, 3.11, 0.0),
                    "col_3": ("Mon", "Tue", "Thu", "Fri", "Mon", "Tue", "Thu")}) 

I want to drop rows where df.col_1 is 1.0 and df.col_2 is 0.0. So, I would get:

df = pd.DataFrame({"col_1": (0.0, 0.0, 1.0, 0.0, 1.0), 
                   "col_2": (0.0, 0.24, 1.0, 0.22, 3.11),
                    "col_3": ("Mon", "Tue", "Thu", "Mon", "Tue")})

I tried:

df_new = df.drop[df[(df['col_1'] == 1.0) & (df['col_2'] == 0.0)].index]

It gives me the error:

'method' object is not subscriptable

Any idea how to solve the above problem?

like image 475
Dsh M Avatar asked Sep 22 '18 12:09

Dsh M


People also ask

How do I delete rows in Pandas Dataframe based on multiple conditions?

Use drop() method to delete rows based on column value in pandas DataFrame, as part of the data cleansing, you would be required to drop rows from the DataFrame when a column value matches with a static value or on another column value.

How do I delete rows from multiple conditions?

To remove rows of data from a dataframe based on multiple conditional statements. We use square brackets [ ] with the dataframe and put multiple conditional statements along with AND or OR operator inside it. This slices the dataframe and removes all the rows that do not satisfy the given conditions.


1 Answers

drop is a method, you are calling it using [], that is why it gives you:

'method' object is not subscriptable

change to () (a normal method call) an it should work:

import pandas as pd

df = pd.DataFrame({"col_1": (0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0),
                   "col_2": (0.0, 0.24, 1.0, 0.0, 0.22, 3.11, 0.0),
                   "col_3": ("Mon", "Tue", "Thu", "Fri", "Mon", "Tue", "Thu")})

df_new = df.drop(df[(df['col_1'] == 1.0) & (df['col_2'] == 0.0)].index)
print(df_new)

Output

   col_1  col_2 col_3
0    0.0   0.00   Mon
1    0.0   0.24   Tue
2    1.0   1.00   Thu
4    0.0   0.22   Mon
5    1.0   3.11   Tue
like image 139
Dani Mesejo Avatar answered Oct 06 '22 07:10

Dani Mesejo