Python coder
Python coder

Reputation: 849

How to create a iterative condition inside np.where?

I have dataframe df and columns list cols_list which need to check the condition.

ex: cols_list = [cols1, cols2, col3]

I need to create new column as shown below,

df['new_col'] = np.where((df['cols1'] == 1) | (df['cols1'] == 1) | (df['cols1'] == 1), 1, 0)

I have multiple cols_list with different length, How can I create this condition (df['cols1'] == 1) | (df['cols1'] == 1) | (df['cols1'] == 1) iteratively for multiple cols_list?

Currently, I need to do it manually, as those kind of cols_list are in hundreds, I was looking for a better way to do it!

Upvotes: 1

Views: 41

Answers (1)

Dani Mesejo
Dani Mesejo

Reputation: 61910

Use:

np.where((df[cols_list].eq(1).any(axis=1), 1, 0))

Upvotes: 1

Related Questions