Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python/Numpy: How do you assign the end+1 element of an array similar to how it's done in Matlab?

For example, for a 1D array with n elements, if I want to do this in Matlab I can do:

A(end+1) = 1

that assigns the value of 1 to the last element of array A which is now n+1 in length.

Is there an equivalent in Python/Numpy?

like image 905
Isopycnal Oscillation Avatar asked Oct 29 '13 19:10

Isopycnal Oscillation


People also ask

How do I assign an element to a NumPy array?

We can assign new values to an element of a NumPy array using the = operator, just like regular python lists. A few examples are below (note that this is all one code block, which means that the element assignments are carried forward from step to step).

How do you add an element to the end of an array in Python?

We can add value to an array by using the append(), extend() and the insert (i,x) functions. The append() function is used when we need to add a single element at the end of the array.

How do I add to the end of a NumPy array?

You can add a NumPy array element by using the append() method of the NumPy module. The values will be appended at the end of the array and a new ndarray will be returned with new and old values as shown above. The axis is an optional integer along which define how the array is going to be displayed.

How do you assign an element to an array in Python?

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. If you are using NumPy arrays, use the append() and insert() function.


2 Answers

You can just append a value to the end of an array/list using append or numpy.append:

# Python list
a = [1, 2, 3]
a.append(1)
# => [1, 2, 3, 1]

# Numpy array
import numpy as np
a = np.array([1, 2, 3])
a = np.append(a, 1)
# => [1, 2, 3, 1]

Note, as pointed out by @BrenBarn, that the numpy.append approach creates a whole new array each time it is executed, which makes it inefficient.

like image 54
mdml Avatar answered Sep 29 '22 17:09

mdml


I bet the Matlab/Octave operation does the same - create a new object. But I don't know if there is something like the Python id(a) to verify that.

A crude timing test in Octave supports this - creating a large array by appending is slower than stepping through the full array. Both are much slower than direct assignment like A=1:N

octave:36> t=time; N=1000000; A=[]; A(N)=1; for i=1:N A(i)=i; end; t-time
ans = -4.0374
octave:37> t=time; N=1000000; A=[]; for i=1:N A(end+1)=i; end; t-time
ans = -15.218

Extending an array with (end+1) is more idiomatic in Javascript than Matlab.

like image 35
hpaulj Avatar answered Sep 29 '22 18:09

hpaulj