13

I need to add a column and a row to an existing Numpy array at a defined position.

2
  • 3
    This needs a little more information Commented Jan 4, 2010 at 21:41
  • 2
    what kind of an array? list of lists, array.array or numpy.array? Commented Jan 4, 2010 at 21:42

3 Answers 3

27

I assume your column and rows are just a list of lists?

That is, you have the following?

L = [[1,2,3],
     [4,5,6]]

To add another row, use the append method of a list.

L.append([7,8,9])

giving

L = [[1,2,3],
     [4,5,6],
     [7,8,9]]

To add another column, you would have to loop over each row. An easy way to do this is with a list comprehension.

L = [x + [0] for x in L]

giving

L = [[1,2,3,0],
     [4,5,6,0]]
Sign up to request clarification or add additional context in comments.

3 Comments

and to convert that to array just do array(lst) ?
That should work. There's probably a better way to do this with numpy, but your original question did not specify such.
np.append takes an axis argument specifying the dimension to append; so the way described for adding a new column is discourage because it is not numpy-optimized.
7

There are many ways to do this in numpy, but not all of them let you add the row/column to the target array at any location (e.g., append only allows addition after the last row/column). If you want a single method/function to append either a row or column at any position in a target array, i would go with 'insert':

T = NP.random.randint(0, 10, 20).reshape(5, 4)
c = NP.random.randint(0, 10, 5)
r = NP.random.randint(0, 10, 4)
# add a column to T, at the front:
NP.insert(T, 0, c, axis=1)
# add a column to T, at the end:
NP.insert(T, 4, c, axis=1)
# add a row to T between the first two rows:
NP.insert(T, 2, r, axis=0)

1 Comment

I am using you solution after a decade and it works perfect for my need. Thanks!
1

I would suggest sympy Matrix object to do it:

a = [[ 2,   1,  180],
     [ 1,   3,  300],
     [-1,  -4,    0]]

b = [[1,0],
     [0,0],
     [0,1]]
import sympy as sp

a = sp.Matrix(a).col_insert(-2, sp.Matrix(b))
a.tolist()

Output:

[[2, 1, 0, 1, 180], 
 [1, 0, 0, 3, 300], 
 [-1, 0, 1, -4, 0]]

And to continue with a Numpy array, you can use np.asarray(a) instead of a.tolist() (assuming you have imported Numpy as np)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.