python - Convert 1D object numpy array of lists to 2D numeric array and back -


say have object array containing lists of same length:

>>> = np.empty(2, dtype=object) >>> a[0] = [1, 2, 3, 4] >>> a[1] = [5, 6, 7, 8] >>> array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=object) 
  1. how can convert numeric 2d array?

    >>> a.shape (2,) >>> b = what_goes_here(a) >>> b array([[1, 2, 3, 4],        [5, 6, 7, 8]]) >>> b.shape (2, 4) 
  2. how can reverse?

  3. does easier if a array np.array of np.arrays, rather np.array of lists?

    >>> na = np.empty(2, dtype=object) >>> na[0] = np.array([1, 2, 3, 4]) >>> na[1] = np.array([5, 6, 7, 8]) >>> na array([array([1, 2, 3, 4]), ([5, 6, 7, 8])], dtype=object) 

one approach using np.concatenate -

b = np.concatenate(a).reshape(len(a),*np.shape(a[0])) 

the improvement suggest @eric use *np.shape(a[0]) should make work generic nd shapes.

sample run -

in [183]: out[183]: array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=object)  in [184]: a.shape out[184]: (2,)  in [185]: b = np.concatenate(a).reshape(len(a),*np.shape(a[0]))  in [186]: b out[186]:  array([[1, 2, 3, 4],        [5, 6, 7, 8]])  in [187]: b.shape out[187]: (2, 4) 

to a, seems can use two-step process, -

a_back = np.empty(b.shape[0], dtype=object) a_back[:] = b.tolist() 

sample run -

in [190]: a_back = np.empty(b.shape[0], dtype=object)      ...: a_back[:] = b.tolist()      ...:   in [191]: a_back out[191]: array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=object)  in [192]: a_back.shape out[192]: (2,) 

Comments

Popular posts from this blog

angular - Is it possible to get native element for formControl? -

unity3d - Rotate an object to face an opposite direction -

javascript - Why jQuery Select box change event is now working? -