ladybug
ladybug

Reputation: 602

Fill a column with multiple conditions from other columns

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}])

Upvotes: 0

Views: 66

Answers (3)

sas21
sas21

Reputation: 49

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

Upvotes: 1

ansev
ansev

Reputation: 30930

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

Upvotes: 2

Ben.T
Ben.T

Reputation: 29635

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

Upvotes: 1

Related Questions