Taa*_*aam 5 python arrays numpy
我需要hstacking具有相同行数的多个数组(尽管行数在使用之间是可变的)但是列数不同.然而,一些阵列仅具有一列,例如.
array = np.array([1,2,3,4,5])
Run Code Online (Sandbox Code Playgroud)
这使
#array.shape = (5,)
Run Code Online (Sandbox Code Playgroud)
但我想将形状识别为二维数组,例如.
#array.shape = (5,1)
Run Code Online (Sandbox Code Playgroud)
因此,hstack实际上可以将它们组合在一起.我目前的解决方案是:
array = np.atleast_2d([1,2,3,4,5]).T
#array.shape = (5,1)
Run Code Online (Sandbox Code Playgroud)
所以我想知道,有更好的方法吗?将
array = np.array([1,2,3,4,5]).reshape(len([1,2,3,4,5]), 1)
Run Code Online (Sandbox Code Playgroud)
会更好?请注意,我对[1,2,3,4,5]的使用只是一个玩具清单,以使示例具体.在实践中,它将是一个更大的列表,作为参数传递给函数.谢谢!
检查的代码hstack和vstack.其中一个或两个都通过论证atleast_nd.这是重塑数组的完全可接受的方式.
其他一些方法:
arr = np.array([1,2,3,4,5]).reshape(-1,1) # saves the use of len()
arr = np.array([1,2,3,4,5])[:,None] # adds a new dim at end
np.array([1,2,3],ndmin=2).T # used by column_stack
Run Code Online (Sandbox Code Playgroud)
hstack并vstack转换他们的输入:
arrs = [atleast_1d(_m) for _m in tup]
[atleast_2d(_m) for _m in tup]
Run Code Online (Sandbox Code Playgroud)
测试数据:
a1=np.arange(2)
a2=np.arange(10).reshape(2,5)
a3=np.arange(8).reshape(2,4)
np.hstack([a1.reshape(-1,1),a2,a3])
np.hstack([a1[:,None],a2,a3])
np.column_stack([a1,a2,a3])
Run Code Online (Sandbox Code Playgroud)
结果:
array([[0, 0, 1, 2, 3, 4, 0, 1, 2, 3],
[1, 5, 6, 7, 8, 9, 4, 5, 6, 7]])
Run Code Online (Sandbox Code Playgroud)
如果你不知道哪个数组是1d,那么column_stack最容易使用.其他需要一个小功能,在应用重塑之前测试维度.
| 归档时间: |
|
| 查看次数: |
8696 次 |
| 最近记录: |