How to add items into a numpy array


I need to accomplish the following task:


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?

4/25/2015 5:22:35 AM

Accepted Answer

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:

for 3-D arrays (the above plus):

for N-D arrays:

2/22/2011 12:41:25 AM

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]])

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow