How to add an extra row and column to an array?

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

+5
python
source share
2 answers

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

So you have the following?

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

To add another line, use the add list method.

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

gives

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

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

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

gives

 L = [[1,2,3,0], [4,5,6,0]] 
+18
source share

There are many ways to do this in numpy, but not all of them allow you to add a row / column to the target array anywhere (for example, append only allows you to add after the last row / column). If you want a single method / function to add a row or column to any position in the 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) 
+6
source share

All Articles