Python – Map 1d numpy arrays to 2d arrays based on element functions

Map 1d numpy arrays to 2d arrays based on element functions… here is a solution to the problem.

Map 1d numpy arrays to 2d arrays based on element functions

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

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

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

Each entry is either 0 or 1. I want to map it to a two-dimensional array by the mapped elements wisely

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

What should I do? I tried

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

But it doesn’t seem to work.

Solution

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

Using float indexes gives an error in the latest version:

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

Integer index, select rows from ref based on index value:

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

This is the case where you can use choose, but it’s more picky about array shapes than the above index:

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 only 2 selections convert to bool value, 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]])

Related Problems and Solutions