Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add items into a numpy array

Tags:

python

numpy

I need to accomplish the following task:

from:

a = array([[1,3,4],[1,2,3]...[1,2,1]]) 

(add one element to each row) to:

a = array([[1,3,4,x],[1,2,3,x]...[1,2,1,x]]) 

I have tried doing stuff like a[n] = array([1,3,4,x])

but numpy complained of shape mismatch. I tried iterating through a and appending element x to each item, but the changes are not reflected.

Any ideas on how I can accomplish this?

like image 423
goh Avatar asked Feb 21 '11 10:02

goh


People also ask

Can you add to 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 add an item 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.

How do I append at the end of NumPy?

NumPy: append() functionThe append() function is used to append values to the end of an given array. Values are appended to a copy of this array. These values are appended to a copy of arr. It must be of the correct shape (the same shape as arr, excluding axis).


2 Answers

Appending data to an existing array is a natural thing to want to do for anyone with python experience. However, if you find yourself regularly appending to large arrays, you'll quickly discover that NumPy doesn't easily or efficiently do this the way a python list will. You'll find that every "append" action requires re-allocation of the array memory and short-term doubling of memory requirements. So, the more general solution to the problem is to try to allocate arrays to be as large as the final output of your algorithm. Then perform all your operations on sub-sets (slices) of that array. Array creation and destruction should ideally be minimized.

That said, It's often unavoidable and the functions that do this are:

for 2-D arrays:

  • np.hstack
  • np.vstack
  • np.column_stack
  • np.row_stack

for 3-D arrays (the above plus):

  • np.dstack

for N-D arrays:

  • np.concatenate
like image 69
Paul Avatar answered Sep 19 '22 20:09

Paul


import numpy as np a = np.array([[1,3,4],[1,2,3],[1,2,1]]) b = np.array([10,20,30]) c = np.hstack((a, np.atleast_2d(b).T)) 

returns c:

array([[ 1,  3,  4, 10],        [ 1,  2,  3, 20],        [ 1,  2,  1, 30]]) 
like image 33
eumiro Avatar answered Sep 23 '22 20:09

eumiro