Map 1d numpy array to 2d array based on element-wise function

I have a numpy array, it has shape=(10000,). Here are the first 5 entries:

labels = data[:, 0]
print(labels.shape)
print(labels[0:5])

# prints 
# (100000,)
# [1. 1. 1. 0. 1.]

Every entry is either 0 or 1. I would like to map this to a 2d array, by an element wise operation which maps

0 -> [1, 0]
1 -> [0, 1]

How do I do this? I tried

labels = np.apply_along_axis(lambda x: [1, 0] if x[0] == 0 else [0, 1], 0, data[:, 0])

but that did not seem to work.

pythonarraysnumpy

Answers

answered 3 months ago Shaido #1

You could try the following

labels = np.array([1,1,1,0,1])
np.eye(np.max(labels) + 1)[labels]

which gives:

array([[ 0.,  1.],
       [ 0.,  1.],
       [ 0.,  1.],
       [ 1.,  0.],
       [ 0.,  1.]])

answered 3 months ago Tai #2

This method does xor on the original array and stack two arrays together.

labels = np.random.randint(0,2, 10000)
# array([0, 0, 1, ..., 1, 1, 0])
np.vstack([(~labels.astype(bool)).astype(int), labels])
array([[1, 1, 0, ..., 0, 0, 1],
       [0, 0, 1, ..., 1, 1, 0]])

answered 3 months ago hpaulj #3

In [435]: ref = np.array([[1,0],[0,1]])
In [436]: index = np.array([1.,1.,1.,0.,1.])

Indexing with floats gives an error in recent versions:

In [437]: ref[index,:]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-437-d50c95668d6c> in <module>()
----> 1 ref[index,:]

IndexError: arrays used as indices must be of integer (or boolean) type

Index with integers, select rows from ref depending on the index value:

In [438]: ref[index.astype(int),:]
Out[438]: 
array([[0, 1],
       [0, 1],
       [0, 1],
       [1, 0],
       [0, 1]])

This is a case where choose could be used, but it's pickier about array shapes than the above indexing:

In [440]: np.choose(index.astype(int)[:,None],[[1,0],[0,1]])
Out[440]: 
array([[0, 1],
       [0, 1],
       [0, 1],
       [1, 0],
       [0, 1]])

or with only 2 choices that convert to boolean, where:

In [443]: np.where(index.astype(bool)[:,None],[0,1],[1,0])
Out[443]: 
array([[0, 1],
       [0, 1],
       [0, 1],
       [1, 0],
       [0, 1]])

comments powered by Disqus