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.

4
  • What have you tried so far, did you get some error? Commented Oct 25, 2019 at 8:38
  • Why are you using numpy for this¿? Commented Oct 25, 2019 at 8: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. Commented Oct 25, 2019 at 8:40
  • Possible duplicate of Cartesian product of x and y array points into single array of 2D points Search this post for the optimized answer. Commented Oct 25, 2019 at 8:46

3 Answers 3

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))])
Sign up to request clarification or add additional context in comments.

Comments

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']]

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.