Ofek Ron
Ofek Ron

Reputation: 8578

numpy where - how to set condition on whole column?

How to implement :

t=np.where(<exists at least 1 zero in the same column of t>,t,np.zeros_like(t))

in the "pythonic" way?

this code should set all column to zero in t if t has at least 1 zero in that column

Example :

1 1 1 1 1 1
0 1 1 1 1 1
1 1 0 1 0 1

should turn to

0 1 0 1 0 1
0 1 0 1 0 1
0 1 0 1 0 1

Upvotes: 0

Views: 168

Answers (2)

kuzand
kuzand

Reputation: 9806

this code should set all column to zero in t if t has at least 1 zero in that column

The simplest way to do this particular task:

t * t.min(0)

A more general way to do it (in case you have an array with different values and the condition is: if a column has at least one occurrence of some_value, then set that column to some_value).

cond = (arr == some_value).any(0)
arr[:, cond] = some_value

Upvotes: 0

Kenan
Kenan

Reputation: 14104

any is what you need

~(arr == 0).any(0, keepdims=True) * arr

0 1 0 1 0 1
0 1 0 1 0 1
0 1 0 1 0 1

Upvotes: 1

Related Questions