Shahrukh Azhar
Shahrukh Azhar

Reputation: 59

Create numpy array within numpy array

I want to create a numpy array within a numpy array. If i do it with normal python its something like

a = [[1,2], [3,4]]

a[0][1] = [1,1,1]

print a

The result is [[1, [1, 1, 1]], [3, 4]]

How can I achieve the same using numpy arrays? The code I have is:

a = np.array([(1, 2, 3),(4, 5, 6)])
b = np.array([1,1,1])

a[0][1] = b

Upvotes: 0

Views: 656

Answers (2)

hpaulj
hpaulj

Reputation: 231530

a as created is dtype int. Each element can only be another integer:

In [758]: a = np.array([(1, 2, 3),(4, 5, 6)])
     ...: b = np.array([1,1,1])
     ...: 
In [759]: a
Out[759]: 
array([[1, 2, 3],
       [4, 5, 6]])
In [760]: b
Out[760]: array([1, 1, 1])
In [761]: a[0,1]=b
...
ValueError: setting an array element with a sequence.

You can make another dtype of array, one that holds pointers to objects, much as list does:

In [762]: aO = a.astype(object)
In [763]: aO
Out[763]: 
array([[1, 2, 3],
       [4, 5, 6]], dtype=object)

Now it is possible to replace one of those element pointers with a pointer to b array:

In [765]: aO[0,1]=b
In [766]: aO
Out[766]: 
array([[1, array([1, 1, 1]), 3],
       [4, 5, 6]], dtype=object)

But as asked in the comments - why do you want/need to do this? What are you going to do with such an array? It is possible to do some numpy math on such an array, but as shown in some recent SO questions, it is hit-or-miss. It is also slower.

Upvotes: 1

jonathanking
jonathanking

Reputation: 652

As far as I know, you cannot do this. Numpy arrays cannot have entries of varying shape. Your request to make an array like [[1, [1, 1, 1]], [3, 4]] is impossible. However, you could make a numpy matrix of dimensions (3x2x3) to get

[
 [
  [1,0,0],
  [1,1,1],
  [0,0,0],
 ]
 [
  [3,0,0],
  [4,0,0],
  [0,0,0]
 ]
]

Your only option is to pad empty elements with some number (I used 0s above) or use another data structure.

Upvotes: 1

Related Questions