0

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.

Lone Lunatic
  • 805
  • 8
  • 20
  • What have you tried so far, did you get some error? – Chris Doyle Oct 25 '19 at 08:38
  • Why are you using numpy for this¿? – yatu Oct 25 '19 at 08:39
  • You can use list comprehension for this task. I would suggest to have a look, or post what you have tried so far, so we can help you better. – Koralp Catalsakal Oct 25 '19 at 08:40
  • Possible duplicate of [Cartesian product of x and y array points into single array of 2D points](https://stackoverflow.com/questions/11144513/cartesian-product-of-x-and-y-array-points-into-single-array-of-2d-points) Search this post for the optimized answer. – Lone Lunatic Oct 25 '19 at 08:46

3 Answers3

1

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))])
Lone Lunatic
  • 805
  • 8
  • 20
1

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']]
yatu
  • 86,083
  • 12
  • 84
  • 139
0

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)
Fei Yao
  • 1,502
  • 10
  • 10