Python Multidimensional Array - Adding additional values to beginning and end of each row
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.
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.
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]]
精彩评论