Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill numpy array with another numpy array

I have an empty numpy array, and another one populated with values. I want to fill the empty numpy array with the populated one, x times. So, when x = 3, the (originally empty array) would look like [[populated_array],[populated_array], [populated_array]]

Where populated_array is the same value/array each time. I have tried this

a = np.empty(3)
a.fill(np.array([4,6,6,1]))

but get this

ValueError: Input object to FillWithScalar is not a scalar

and want this

[[4,6,6,1],[4,6,6,1],[4,6,6,1]]

cheers for any help.

like image 871
harry lakins Avatar asked Dec 08 '16 17:12

harry lakins


2 Answers

tile and repeat are handy functions when you want to repeat an array in various ways:

In [233]: np.tile(np.array([4,6,6,1]),(3,1))
Out[233]: 
array([[4, 6, 6, 1],
       [4, 6, 6, 1],
       [4, 6, 6, 1]])

On the failure, note the docs for fill:

a.fill(value)

Fill the array with a scalar value.

np.array([4,6,6,1]) is not a scalar value. a was initialized as a 3 element float array.

It is possible to assign values to elements of an array, provided the shapes are right:

In [241]: a=np.empty(3)
In [242]: a[:]=np.array([1,2,3])    # 3 numbers into 3 slots
In [243]: a
Out[243]: array([ 1.,  2.,  3.])
In [244]: a=np.empty((3,4))
In [245]: a[:]=np.array([1,2,3,4])   # 4 numbers into 4 columns
In [246]: a
Out[246]: 
array([[ 1.,  2.,  3.,  4.],
       [ 1.,  2.,  3.,  4.],
       [ 1.,  2.,  3.,  4.]])

This fill works with an object type array, but the result is quite different, and should be used with considerable caution:

In [247]: a=np.empty(3, object)
In [248]: a
Out[248]: array([None, None, None], dtype=object)
In [249]: a.fill(np.array([1,2,3,4]))
In [250]: a
Out[250]: array([array([1, 2, 3, 4]), array([1, 2, 3, 4]), array([1, 2, 3, 4])], dtype=object)

This (3,) array is not the same as the (3,4) array produced by other methods. Each element of the object array is a pointer to the same thing. Changing a value in one element of a changes that value in all the elements (because they are the same object).

In [251]: a[0][3]=5
In [252]: a
Out[252]: array([array([1, 2, 3, 5]), array([1, 2, 3, 5]), array([1, 2, 3, 5])], dtype=object)
like image 54
hpaulj Avatar answered Oct 06 '22 07:10

hpaulj


Use broadcasting

vstack, tile, and repeat are all great and whatnot, but broadcasting can be several orders of magnitude faster...

import numpy as np
from time import time

t = time()
for _ in xrange(10000):
    a = np.array([4,6,6,1])
    b = np.vstack((a,)*100)
print time()-t

t = time()
for _ in xrange(10000):
    a = np.array([4,6,6,1])
    b = np.tile(a,(3,1))
print time()-t

t = time()
for _ in xrange(10000):
    a = np.array([4,6,6,1])
    b = np.empty([100,a.shape[0]])
    b[:] = a
print time()-t

prints:

2.76399993896
0.140000104904
0.0490000247955
like image 28
Aaron Avatar answered Oct 06 '22 08:10

Aaron