2011-10-03 64 views
6

我想塑造一個形狀(n,)形狀(n,1)numpy ndarray對象。我想出的最好的是推出自己的_to_col功能:numpy:將(n,)數組轉換爲(n,1)數組的語法/成語?

def _to_col(a): 
    return a.reshape((a.size, 1)) 

但是,我很難相信這樣一個無處不在的操作是不是已經內置到numpy的語法。我想我只是無法在正確的Google搜索中找到它。

回答

9

我會使用以下方法:

a[:,np.newaxis] 

另一種(但可能略少清)的方式來寫同樣的事情是:

a[:,None] 

上述所有的(包括你的版本)是恆定時間的操作。

+0

貶低的陣列的軸線添加到2D或更高次數組的末尾,使用省略號代替冒號: 'a [...,None]',它涵蓋了必要的尺寸。然後'a.shape'將從例如'(n,m)'到'(n,m,1)'。 – askewchan

2

當我想添加任意軸時,np.expand_dims是我的最愛。

無或np.newaxis適用於不需要靈活軸的代碼。 (AIX的回答)

>>> np.expand_dims(np.arange(5), 0).shape 
(1, 5) 
>>> np.expand_dims(np.arange(5), 1).shape 
(5, 1) 

示例用法:由任何給定的軸線

>>> x = np.random.randn(4,5) 
>>> x - x.mean(1) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ValueError: shape mismatch: objects cannot be broadcast to a single shape 


>>> ax = 1 
>>> x - np.expand_dims(x.mean(ax), ax) 
array([[-0.04152658, 0.4229244 , -0.91990969, 0.91270622, -0.37419434], 
     [ 0.60757566, 1.09020783, -0.87167478, -0.22299015, -0.60311856], 
     [ 0.60015774, -0.12358954, 0.33523495, -1.1414706 , 0.32966745], 
     [-1.91919832, 0.28125008, -0.30916116, 1.85416974, 0.09293965]]) 
>>> ax = 0 
>>> x - np.expand_dims(x.mean(ax), ax) 
array([[ 0.15469413, 0.01319904, -0.47055919, 0.57007525, -0.22754506], 
     [ 0.70385617, 0.58054228, -0.52226447, -0.66556131, -0.55640947], 
     [ 1.05009459, -0.27959876, 1.03830159, -1.23038543, 0.73003287], 
     [-1.90864489, -0.31414256, -0.04547794, 1.32587149, 0.05392166]])