filipnov
filipnov

Reputation: 33

Pandas: create column based on whether value exists in differents columns

I'd like to create a new column based on these conditions:

Is there a better way how to do this? Thx

df = pd.DataFrame([['a', np.nan, 100], ['b', 20, np.nan], ['c', 30, 300], ['d', np.nan, np.nan]])


df['is_1'] =  np.where(df[1].notnull(), 1, 0)
df['is_2'] =  np.where(df[2].notnull(), 100, 0)
df['sum'] = df['is_1'] + df['is_2']

Upvotes: 3

Views: 313

Answers (1)

jpp
jpp

Reputation: 164673

Just note Boolean values translate to 0 / 1 for computations:

df['sum'] = df[1].notnull() + df[2].notnull() * 100

Upvotes: 2

Related Questions