给定以下二维数组:
a = np.array([
[1, 2, 3],
[2, 3, 4],
])
我想在第二轴上加上一列0,得到:
b = np.array([
[1, 2, 3, 0],
[2, 3, 4, 0],
])
给定以下二维数组:
a = np.array([
[1, 2, 3],
[2, 3, 4],
])
我想在第二轴上加上一列0,得到:
b = np.array([
[1, 2, 3, 0],
[2, 3, 4, 0],
])
当前回答
对我来说,下一种方法看起来非常直观和简单。
zeros = np.zeros((2,1)) #2 is a number of rows in your array.
b = np.hstack((a, zeros))
其他回答
在我的例子中,我必须向NumPy数组中添加一列1
X = array([ 6.1101, 5.5277, ... ])
X.shape => (97,)
X = np.concatenate((np.ones((m,1), dtype=np.int), X.reshape(m,1)), axis=1)
后 X.shape => (97,2)
array([[ 1. , 6.1101],
[ 1. , 5.5277],
...
对我来说,下一种方法看起来非常直观和简单。
zeros = np.zeros((2,1)) #2 is a number of rows in your array.
b = np.hstack((a, zeros))
使用numpy.append:
>>> a = np.array([[1,2,3],[2,3,4]])
>>> a
array([[1, 2, 3],
[2, 3, 4]])
>>> z = np.zeros((2,1), dtype=int64)
>>> z
array([[0],
[0]])
>>> np.append(a, z, axis=1)
array([[1, 2, 3, 0],
[2, 3, 4, 0]])
我认为:
np.column_stack((a, zeros(shape(a)[0])))
更优雅。
有点晚了,但还没有人发布这个答案,所以为了完整起见:你可以在一个普通的Python数组上使用列表推导式来完成:
source = a.tolist()
result = [row + [0] for row in source]
b = np.array(result)