Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 307
Heiko Herlich Avatar asked Nov 20 '13 16:11

Heiko Herlich


People also ask

How do you add a value to an array in Python?

If you are using List as an array, you can use its append(), insert(), and extend() functions. You can read more about it at Python add to List. If you are using array module, you can use the concatenation using the + operator, append(), insert(), and extend() functions to add elements to the array.


2 Answers

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])
like image 84
askewchan Avatar answered Oct 19 '22 05:10

askewchan


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

np.hstack((0,a))
like image 12
atomh33ls Avatar answered Oct 19 '22 07:10

atomh33ls