I have two numpy arrays A and B.
A = np.array ([[ 1 3] [ 2 3] [ 2 1] ])
B = np.array([(1, 'Alpha'), (2, 'Beta'), (3, 'Gamma')]
How can I map A with B in order to get something like:
result = np.array ([[ 'Alpha' 'Gamma'] [ 'Beta' 'Gamma'] ['Beta' 'Alpha'] ])
I have tried map(B['f1'],A)
but I am getting TypeError: 'numpy.ndarray' object is not callable
Joining means putting contents of two or more arrays in a single array. In SQL we join tables based on a key, whereas in NumPy we join arrays by axes. We pass a sequence of arrays that we want to join to the concatenate() function, along with the axis. If axis is not explicitly passed, it is taken as 0.
To map multiple arrays with JavaScript, we can use the map method. to define the zip function that calls a1. map to combine the entries from a1 and a2 with index i into one entry. Then we call zip with arr1 and arr2 to zip them into one array.
To add the two arrays together, we will use the numpy. add(arr1,arr2) method. In order to use this method, you have to make sure that the two arrays have the same length. If the lengths of the two arrays are not the same, then broadcast the size of the shorter array by adding zero's at extra indexes.
Here's a NumPythonic
vectorized approach -
B[:,1][(A == B[:,0].astype(int)[:,None,None]).argmax(0)]
Sample run on a generic case -
In [118]: A
Out[118]:
array([[4, 3],
[2, 3],
[2, 4]])
In [119]: B
Out[119]:
array([['3', 'Alpha'],
['4', 'Beta'],
['2', 'Gamma']],
dtype='|S5')
In [120]: B[:,1][(A == B[:,0].astype(int)[:,None,None]).argmax(0)]
Out[120]:
array([['Beta', 'Alpha'],
['Gamma', 'Alpha'],
['Gamma', 'Beta']],
dtype='|S5')
You can use a dictionary and a list comprehension :
>>> d=dict(B)
>>> np.array([[(d[str(i)]),d[str(j)]] for i,j in A])
array([['Alpha', 'Gamma'],
['Beta', 'Gamma'],
['Beta', 'Alpha']],
dtype='|S5')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With