Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How do I add 0's to the beginning and end of each row of a multidimensional array? This is the function I am trying to apply to each row.

def zero(ltr):
  for x in range (1,int((N+1)/2)):
        ltr = append(([0]), ltr)
        ltr = append(ltr,([0]))
  return ltr 

I have tried using both

for row in a:
   zero(row)

and apply_along_axis(zero,1,a) Neither one of these commands does what I want.

share|improve this question

2 Answers 2

up vote 3 down vote accepted

It is not possible to add entries to single rows of a two-dimensional array. All rows must always have the same length. But you can add entries to all rows at once.

If a is a two-dimensional NumPy array, you can use numpy.hstack to add zeros to left and the right:

a = numpy.array([[  0.,   1.,   2.,   3.],
                 [  4.,   5.,   6.,   7.],
                 [  8.,   9.,  10.,  11.]])
numpy.hstack((numpy.zeros((a.shape[0], 2)), a, numpy.zeros((a.shape[0], 1))))
# array([[  0.,   0.,   0.,   1.,   2.,   3.,   0.],
#        [  0.,   0.,   4.,   5.,   6.,   7.,   0.],
#        [  0.,   0.,   8.,   9.,  10.,  11.,   0.]])

For the sake of example, I added 2 zeros to the left and 1 zero to the right.

share|improve this answer

EDIT: I see you're already using numpy. I'll leave this for the sake of education, but you should use hstack as in Sven's answer.

>>> a = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
>>> for row in a:
...     row.insert(0, 0)
...     row.append(0)
...
>>> a
[[0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0]]

or if you prefer:

>>> import operator
>>> a = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
>>> map(operator.methodcaller("insert", 0, 0), a)
[None, None, None]
>>> map(operator.methodcaller("append", 0), a)
[None, None, None]
>>> a
[[0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0]]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.