djskj189
djskj189

Reputation: 295

Panda Dataframe: Check if row satisfies multiple column filters

Is there any way to check if certain rows in the dataframe satisfy multiple filters? I would like to find rows that satisfy filters and add extra values if they pass the filters.

For example,

a b c d e f
2000-01-01 1 1 2  
2000-01-02 0 0 0  
2000-01-03 1 -2 -1  
2000-01-04 5 -5 -2  
2000-01-05 0 -5 0  
2000-01-06 0 0 0  
2000-01-07 5 -2 6  
2000-01-08 0 0 0  

Consider the dataframe with columns a, b, c, d, e, f (d,e,f are empty). How can I do something like:

if (df['a'] == 0 AND df['b'] == 0 AND df['c'] == 0):
  df['d'] = 0
  df['e'] = 0
  df['f'] = 0

So row 2, 6, and 8 should have 0s in columns d, e, f, and the rest of the rows should have empty values in those columns

Thanks!

Upvotes: 1

Views: 6474

Answers (1)

akuiper
akuiper

Reputation: 214957

You can use vectorized and & to create a logical vector for indexing and assignment:

df.loc[(df.a == 0) & (df.b == 0) & (df.c == 0), list('def')] = 0

enter image description here

Update: if the values for d,e,f are different, you can do something like:

df.loc[(df.a == 0) & (df.b == 0) & (df.c == 0), list('def')] = 1,2,3

enter image description here

Upvotes: 3

Related Questions