Carmellose
Carmellose

Reputation: 5088

numpy 1D array to numpy arrays

I'd like to read a 1D numpy array in Python and generate two other numpy arrays:

For example:

a = numpy.array([1,2,numpy.nan,4])

would give

[1,2,0,4]
[1,1,0,1]

What's the most efficient way to do this in python ?

Thanks

Upvotes: 0

Views: 197

Answers (3)

falsetru
falsetru

Reputation: 368924

To replace nan to 0, use numpy.nan_to_num:

>>> a = numpy.array([1,2,numpy.nan,4])
>>> numpy.nan_to_num(a)
array([ 1.,  2.,  0.,  4.])

Use numpy.isnan to convert nan to True, non-nan numbers to False. Then substract them from 1.

>>> numpy.isnan(a)
array([False, False,  True, False], dtype=bool)
>>> 1 - numpy.isnan(a)
array([ 1.,  1.,  0.,  1.])

Upvotes: 1

irenemeanspeace
irenemeanspeace

Reputation: 301

To convert NaNs to zeros, use:

numpy.nan_to_num(a)

To set 1 for non-NaNs and 0 for NaNs, try:

numpy.isfinite(a)*1

Upvotes: 0

VIKASH JAISWAL
VIKASH JAISWAL

Reputation: 838

for first one:

numpy.nan_to_num(a)

second one:

numpy.invert(numpy.isnan(a)).astype(int)

Upvotes: 0

Related Questions