Ron Mercer
Ron Mercer

Reputation: 47

Remove row in dataframe with conditions

Here is my dataframe:

       ID  Tell  Number 
0       1   Perhaps 2   
1       1   Yes     6
2       1   No      9
3       2   Yes     4
4       2   Ye      7
5       2   No      8
6       3   Ye     15
7       3   Perhaps 2
8       3   No      6
9       3   Yes     2 

# Creating the dictionary
dic = {'ID': [1,1,1,2,2,2,3,3,3,3], 'Tell': ['Perhaps', 'Yes', 'No', 'Yes','Ye', 'No','Ye', 'Perhaps','No', 'Yes'], 'Number': [3,6,9,4,7,8,15,8,6,13]}

# Creating the dataframe
df = pd.DataFrame(dic)

I want my program to be able to remove every row from my dataframe if the number is higher then 6 and the Tell column is either Ye or Yes.

I want it to look like that:

       ID  Tell  Number 
0       1   Yes     2   
1       1   Yes     6
2       1   No      9
3       2   Yes     4
4       2   No      8
5       3   Yes     2
6       3   No      6
7       3   Yes     2 

Here is what I have tried:

df=df.loc[((df['Number'] < 6) & (df['Tell']!='ye')& (df['Observation']!='Yes'))]

Upvotes: 1

Views: 85

Answers (3)

Nethra Gunti
Nethra Gunti

Reputation: 3

There might be an error in this line:

df=df.loc[((df['Number'] < 6) & (df['Tell']!='ye')& (df['Observation']!='Yes'))]

I see that there is no Observation column and also your df has Ye and you have ye your condition. That might be the issue possibly. So try capitalizing ye to Ye and Observation to Tell

df=df.loc[((df['Number'] < 6) & (df['Tell']!='Ye')& df['Tell']!='Yes'))]

Let me know if that was the issue.

Upvotes: 0

wwnde
wwnde

Reputation: 26676

Just in case you have a column Observation which you have not given us. Try;

 df[(df['Number']<6)&(df['Tell']!='Ye')&(df['Observation']!='Yes')]

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195408

You can use df.query:

print( df.query('not (Number > 6 and Tell in ["Ye", "Yes"])') )

Prints:

   ID     Tell  Number
0   1  Perhaps       3
1   1      Yes       6
2   1       No       9
3   2      Yes       4
5   2       No       8
7   3  Perhaps       8
8   3       No       6

Upvotes: 1

Related Questions