擅长:python、mysql、java
<p>检查<code>hstack</code>和<code>vstack</code>的代码。其中一个或两个,通过<code>atleast_nd</code>传递参数。这是一种完全可以接受的重塑数组的方法。</p>
<p>其他一些方式:</p>
<pre><code>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
</code></pre>
<hr/>
<p><code>hstack</code>和<code>vstack</code>将它们的输入转换为:</p>
<pre><code>arrs = [atleast_1d(_m) for _m in tup]
[atleast_2d(_m) for _m in tup]
</code></pre>
<hr/>
<p>测试数据:</p>
<pre><code>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])
</code></pre>
<p>结果:</p>
<pre><code>array([[0, 0, 1, 2, 3, 4, 0, 1, 2, 3],
[1, 5, 6, 7, 8, 9, 4, 5, 6, 7]])
</code></pre>
<p>如果您不提前知道哪些数组是1d,那么<code>column_stack</code>是最容易使用的。另一些则需要一个小函数,在应用整形之前测试维度。</p>
<p><a href="https://stackoverflow.com/questions/28385666/numpy-use-reshape-or-newaxis-to-add-dimensions">Numpy: use reshape or newaxis to add dimensions</a></p>