Ale*_*vin 1 python arrays numpy reshape
我有一个数组:
X = [[2, 2, 2],
[3, 3, 3],
[4, 4, 4]]
Run Code Online (Sandbox Code Playgroud)
我需要在 numpy 数组中添加额外的列,并使用 hstack 和 reshape 填充它。像那样:
X = [[2, 2, 2, 1],
[3, 3, 3, 1],
[4, 4, 4, 1]]
Run Code Online (Sandbox Code Playgroud)
我所做的:
X = np.hstack(X, np.ones(X.reshape(X, (2,3))))
Run Code Online (Sandbox Code Playgroud)
并得到一个错误:
TypeError: only length-1 arrays can be converted to Python scalars
Run Code Online (Sandbox Code Playgroud)
有什么问题?我做错了什么?
这是使用numpy.append, numpy.hstackor的几种方法numpy.column_stack:
# numpy is imported as np
>>> x
array([[2, 2, 2],
[3, 3, 3],
[4, 4, 4]])
>>> np.append(x, np.ones([x.shape[0], 1], dtype=np.int32), axis=1)
array([[2, 2, 2, 1],
[3, 3, 3, 1],
[4, 4, 4, 1]])
>>> np.hstack([x, np.ones([x.shape[0], 1], dtype=np.int32)])
array([[2, 2, 2, 1],
[3, 3, 3, 1],
[4, 4, 4, 1]])
>>> np.column_stack([x, np.ones([x.shape[0], 1], dtype=np.int32)])
array([[2, 2, 2, 1],
[3, 3, 3, 1],
[4, 4, 4, 1]])
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以使用numpy.insert():
>>> X
array([[2, 2, 2],
[3, 3, 3],
[4, 4, 4]])
Run Code Online (Sandbox Code Playgroud)
矩阵开头的那些:
>>> X=np.insert(X,0,1.0,axis=1)
>>> X
array([[1, 2, 2, 2],
[1, 3, 3, 3],
[1, 4, 4, 4]])
Run Code Online (Sandbox Code Playgroud)
矩阵末尾的那些
>>> X=np.insert(X,3,1.0,axis=1)
>>> X
array([[2, 2, 2, 1],
[3, 3, 3, 1],
[4, 4, 4, 1]])
Run Code Online (Sandbox Code Playgroud)