0

Is it possible to fill a column according to other conditions?

I made a false algorithm:

if (df.b == 3) & (df.c == 0) & (df.a == None):
    df['d'] == 0
else:
    df['b']

and I tried

import pandas

df = pandas.DataFrame([{'a': None, 'b': 3, 'c': 0},
           {'a': "string", 'b': 0, 'c': 3},
           {'a': "string", 'b': 3, 'c': 0}])

df['d'] = [0 if ((df.b == 3) & (df.c == 0) & (df.a == None)) else pass]

SyntaxError: invalid syntax

I need

df = pandas.DataFrame([{'a': None, 'b': 3, 'c': 0, 'd': 0},
           {'a': "string", 'b': 0, 'c': 3, 'd': 0},
           {'a': "string", 'b': 3, 'c': 0, 'd': 3}])
ladybug
  • 572
  • 2
  • 4
  • 13

3 Answers3

2

IIUC, Series.mask

df['d'] = df['b'].mask(df['b'].eq(3) & df['c'].eq(0) & df['a'].isnull(), 0)

print (df)
        a  b  c  d
0    None  3  0  0
1  string  0  3  0
2  string  3  0  3
ansev
  • 30,322
  • 5
  • 17
  • 31
  • Alternative: `df.apply(lambda x:0 if x[0]==None and x[1]==3 and x[2]==0 else x[1],axis=1)` this is not better than yours. Nice answer. already +1ed – Ch3steR May 19 '20 at 18:34
  • Thanks : ), I think we shouldn't use apply here, https://stackoverflow.com/questions/54432583/when-should-i-ever-want-to-use-pandas-apply-in-my-code @ Ch3steR – ansev May 19 '20 at 18:36
  • You are welcome:) I used to always use apply, it is a very common mistake, now I always think twice.. @Ch3steR – ansev May 19 '20 at 18:39
1

you can use np.where and isnullto get where a is None.

import numpy as np

df['d'] = np.where((df.b == 3) & (df.c == 0) & (df.a.isnull()), 0, df['b'])
print (df)
        a  b  c  d
0    None  3  0  0
1  string  0  3  0
2  string  3  0  3
Ben.T
  • 29,160
  • 6
  • 32
  • 54
1

df['d'] = df['b'].mask(df['b'].eq(3) & df['c'].eq(0) & df['a'].isnull(), 0)

print (df) a b c d 0 None 3 0 0 1 string 0 3 0 2 string 3 0 3

sas21
  • 29
  • 4