Reputation: 11
If I have a numpy array with objects such as the following:
array(['Ana', 'Charlie', 'Andrew'], dtype=object)
And I want to map each object to all objects in the array so I obtain the following output:
array(['Ana', 'Ana'],['Ana','Charlie'],['Ana', 'Andrew'],
['Charlie','ana'], ['Charlie','Charlie'],['Charlie','Andrew'], ['Andrew','ana'],['Andrew', 'Charlie'], ['Andrew','Andrew'], dtype=object).
how can I use numpy to map each object to all objects in the same array?
Thanks so much.
Upvotes: 0
Views: 169
Reputation: 1742
The following code taking advantage of list comprehension should work fine.
import numpy as np
a=np.array(['Ana', 'Charlie', 'Andrew'], dtype=object)
b=np.array([[i,j] for i in a for j in a], dtype=object)
Upvotes: 0
Reputation: 88236
Python lists are generally more suited when dealing with strings. Looks like you want the cartesian product:
from itertools import product
l = ['Ana', 'Charlie', 'Andrew']
list(map(list, product(l,l)))
[['Ana', 'Ana'],
['Ana', 'Charlie'],
['Ana', 'Andrew'],
['Charlie', 'Ana'],
['Charlie', 'Charlie'],
['Charlie', 'Andrew'],
['Andrew', 'Ana'],
['Andrew', 'Charlie'],
['Andrew', 'Andrew']]
Upvotes: 1
Reputation: 835
You are searching for the cartesian product of the two arrays.
numpy.transpose()
should do the trick:
x = array(['Ana', 'Charlie', 'Andrew'], dtype=object)
numpy.transpose([numpy.tile(x, len(x)), numpy.repeat(x, len(x))])
Upvotes: 1