Convert a numpy array to an array of numpy arrays

前端 未结 2 1030
醉酒成梦
醉酒成梦 2021-01-17 03:19

How can I convert numpy array a to numpy array b in a (num)pythonic way. Solution should ideally work for arbitrary dimensions and array lengths.

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-17 04:00

    Based on hpaulj I provide a litte more generic solution. a is an array of dimension N which shall be converted to an array b of dimension N1 with dtype object holding arrays of dimension (N-N1). In the example N equals 5 and N1 equals 3.

    import numpy as np
    
    N=5
    N1=3
    
    #create array a with dimension N
    a=np.random.random(np.random.randint(2,20,size=N))
    
    a_shape=a.shape
    b_shape=a_shape[:N1] # shape of array b
    b_arr_shape=a_shape[N1:] # shape of arrays in b
    
    #Solution 1 with list() method (faster)
    b=np.empty(np.prod(b_shape),dtype=object) #init b
    b[:]=list(a.reshape((-1,)+b_arr_shape))
    b=b.reshape(b_shape)
    
    print "Dimension of b: {}".format(len(b.shape)) # dim of b
    print "Dimension of array in b: {}".format(len(b[0,0,0].shape)) # dim of arrays in b
    
    #Solution 2 with ndindex loop (slower)
    b=np.empty(b_shape,dtype=object)
    for index in np.ndindex(b_shape):
      b[index]=a[index]
    
    print "Dimension of b: {}".format(len(b.shape)) # dim of b
    print "Dimension of array in b: {}".format(len(b[0,0,0].shape)) # dim of arrays in b
    

提交回复
热议问题