2017-04-25 9 views
3

誰かがnp.atleast_3d()の動作を私に説明できますか?numpy atleast_3d()の動作

np.atleast_2d()を使用してから私は、ISは、それが最後の次元に渡されるものは何でも入れながらnp.newaxisを追加することに似ていたと思った:

np.atleast_2d(3.0) 
>>> array([[ 3.]]) 

np.atleast_2d([1.0, 2.0, 3.0]) 
>>> array([[1.0, 2.0, 3.0]]) 

しかしnp.atleast_3d()は非常に動作するようです異なる

np.atleast_3d([[2.9, 3.0]]) 
>>> array([[[ 2.9], 
      [ 3. ]]]) 

ドキュメントは(私が期待しているだろう

For example, a 1-D array of shape (N,) becomes a view of shape (1, N, 1), 
and a 2-D array of shape (M, N) becomes a view of shape (M, N, 1). 

を述べてM、N)が(1,1、N、1)になるように(0120)ここで

+1

を使用しています。次元の数によって異なることがあります。 – hpaulj

答えて

2

atleast_2dからの抜粋です:

if len(ary.shape) == 0: 
     result = ary.reshape(1, 1) 
    elif len(ary.shape) == 1: 
     result = ary[newaxis,:] 
    else: 
     result = ary 

配列は1Dであれば、それはnewaxisトリックを使用しています。 3Dを

if len(ary.shape) == 0: 
     result = ary.reshape(1, 1, 1) 
    elif len(ary.shape) == 1: 
     result = ary[newaxis,:, newaxis] 
    elif len(ary.shape) == 2: 
     result = ary[:,:, newaxis] 
    else: 
     result = ary 

それはあまりにもnewaxisトリックを使用しますが、1のための異なる方法および2Dアレイです。それは、ドキュメントが言うことをします。

形状を変更するには他にも方法があります。例えば、column_stack

array(arr, copy=False, subok=True, ndmin=2).T 

expand_dimsを使用していますあなたは `np.source(np.atleast_3d)`で実際のコードを見ることができます

a.reshape(shape[:axis] + (1,) + shape[axis:]) 
+0

@Joeはあなたがそれを受け入れるほどの答えが好きなら、投票を検討してください! – uhoh

関連する問題