Heiko Herlich
Heiko Herlich

Reputation: 333

python, numpy; How to insert element at the start of an array

I have an numpy array of complex numbers. So I want to insert zero at start of the array, and shift the rest of the array one place forward.

example:

a = [1 + 2j, 5 + 7j,..]

I want to make:

a = [0 + 0j, 1 + 2j, 5 + 7j,..]

What's the simplest way to do this?

Upvotes: 26

Views: 65777

Answers (5)

askewchan
askewchan

Reputation: 46578

Simplest way:

a = np.array([1 + 2j, 5 + 7j])
a = np.insert(a, 0, 0)

Then:

>>> a
array([ 0.+0.j,  1.+2.j,  5.+7.j])

Note that this creates a new array, it does not actually insert the 0 into the original array.

There are several alternatives to np.insert, all of which also create a new array:

In [377]: a
Out[377]: array([ 1.+2.j,  5.+7.j])

In [378]: np.r_[0, a]
Out[378]: array([ 0.+0.j,  1.+2.j,  5.+7.j])

In [379]: np.append(0, a)
Out[379]: array([ 0.+0.j,  1.+2.j,  5.+7.j])

In [380]: np.concatenate([[0], a])
Out[380]: array([ 0.+0.j,  1.+2.j,  5.+7.j])

In [381]: np.hstack([0, a])
Out[381]: array([ 0.+0.j,  1.+2.j,  5.+7.j])

In [382]: np.insert(a, 0, 0)
Out[382]: array([ 0.+0.j,  1.+2.j,  5.+7.j])

Upvotes: 38

W. Zhu
W. Zhu

Reputation: 825

I timed all the five different methods to insert an element at the beginning of an array. Here are the results:

In [20]: %timeit np.hstack([1, [1, 2, 3]])
10000 loops, best of 3: 30.4 µs per loop

In [21]: %timeit np.insert([1, 2, 3], 0, 1)
10000 loops, best of 3: 46.6 µs per loop

In [22]: %timeit np.r_[[1], [1, 2, 3]]
10000 loops, best of 3: 32.8 µs per loop

In [28]: %timeit np.append(1, [1, 2, 3])
10000 loops, best of 3: 23.4 µs per loop

In [29]: %timeit np.concatenate([[1], [1, 2, 3]])
The slowest run took 6.43 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 8.79 µs per loop

Upvotes: 2

kwant
kwant

Reputation: 248

Additionally, if you want to add n numbers of rows with zero values. you can create a zero array and use hstack:

zero_array = np.zeros([n])
new = np.hstack([zero_array,old_array])

Upvotes: -1

tsando
tsando

Reputation: 4717

Also, if you have an n-dimensional array, you need to specify the axis as well, otherwise it gets flattened out:

 np.insert(my_array, 0, myvalue, axis=1)

Upvotes: 3

Lee
Lee

Reputation: 31090

An alternative is "horizontal stack" (also creates a new array):

np.hstack((0,a))

Upvotes: 13

Related Questions