Numpy reshape 1d to 2d array with 1 column

后端 未结 7 621
一生所求
一生所求 2020-12-08 15:08

In numpy the dimensions of the resulting array vary at run time. There is often confusion between a 1d array and a 2d array with 1 column. In one case I can ite

7条回答
  •  我在风中等你
    2020-12-08 15:15

    I asked about dtype because your example is puzzling.

    I can make a structured array with 3 elements (1d) and 3 fields:

    In [1]: A = np.ones((3,), dtype='i,i,i')
    In [2]: A
    Out[2]: 
    array([(1, 1, 1), (1, 1, 1), (1, 1, 1)], 
          dtype=[('f0', '

    I can access one field by name (adding brackets doesn't change things)

    In [3]: A['f0'].shape
    Out[3]: (3,)
    

    but if I access 2 fields, I still get a 1d array

    In [4]: A[['f0','f1']].shape
    Out[4]: (3,)
    In [5]: A[['f0','f1']]
    Out[5]: 
    array([(1, 1), (1, 1), (1, 1)], 
          dtype=[('f0', '

    Actually those extra brackets do matter, if I look at values

    In [22]: A['f0']
    Out[22]: array([1, 1, 1], dtype=int32)
    In [23]: A[['f0']]
    Out[23]: 
    array([(1,), (1,), (1,)], 
          dtype=[('f0', '

    If the array is a simple 2d one, I still don't get your shapes

    In [24]: A=np.ones((3,3),int)
    In [25]: A[0].shape
    Out[25]: (3,)
    In [26]: A[[0]].shape
    Out[26]: (1, 3)
    In [27]: A[[0,1]].shape
    Out[27]: (2, 3)
    

    But as to question of making sure an array is 2d, regardless of whether the indexing returns 1d or 2, your function is basically ok

    def reshape_to_vect(ar):
        if len(ar.shape) == 1:
          return ar.reshape(ar.shape[0],1)
        return ar
    

    You could test ar.ndim instead of len(ar.shape). But either way it is not costly - that is, the execution time is minimal - no big array operations. reshape doesn't copy data (unless your strides are weird), so it is just the cost of creating a new array object with a shared data pointer.

    Look at the code for np.atleast_2d; it tests for 0d and 1d. In the 1d case it returns result = ary[newaxis,:]. It adds the extra axis first, the more natural numpy location for adding an axis. You add it at the end.

    ar.reshape(ar.shape[0],-1) is a clever way of bypassing the if test. In small timing tests it faster, but we are talking about microseconds, the effect of a function call layer.

    np.column_stack is another function that creates column arrays if needed. It uses:

     if arr.ndim < 2:
            arr = array(arr, copy=False, subok=True, ndmin=2).T
    

提交回复
热议问题