I have the following dataframe 'df':
df = pd.DataFrame({'a':[0,2,3],'b':[1,3,4],'c':[4,1,2]})
Now I want to drop such rows such that that row has 0 value for column'a' and non zero value for column 'b'. How can I do that?
I tried this, df = df[df['a'] == 0 and df['b'] != 0]
, but got error.
CodePudding user response:
You're almost there. You need to use &
instead of and
when chaining conditions inside a Pandas .loc
.
df = pd.DataFrame({'a':[0,2,3],'b':[1,3,4],'c':[4,1,2]})
df = df[(df['a'] == 0) & (df['b'] != 0)]
Result:
a b c
0 0 1 4
CodePudding user response:
import pandas library
import pandas as pd
df = pd.DataFrame({'a':[0,2,3],'b':[1,3,4],'c':[4,1,2]})
df ## data of dataframe
take any rows which are having 0 in any columns
df = df[(df['a'] == 0) | (df['b'] == 0)]
CodePudding user response:
For combining conditions in pandas you need to use the bitwise &
operator. e.g:
condtion_a = df.a == 0
condtion_b = df.b != 0
condition = condtion_a & condtion_b
df = df[condition]
Or in a one liner:
df = df[(df.a == 0) & (df.b != 0)]
Bonus: here is a nice explanation