How do I unpack a numpy array of tuples into an ndarray?

后端 未结 2 1670
不思量自难忘°
不思量自难忘° 2021-01-22 03:02

I have a 2D numpy array with elements of the type np.void that are essentially tuples. Is there an efficient way to unpack the values in these tuples to a 3rd dime

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-22 03:36

    You can view as a standard numpy array to allow for the indexing you're after.

    b = a.view('(3,)

    array([[[1, 2, 3],
            [1, 2, 3],
            [1, 2, 3]],
    
           [[1, 2, 3],
            [1, 2, 3],
            [1, 2, 3]],
    
           [[1, 2, 3],
            [1, 2, 3],
            [1, 2, 3]]], dtype=uint16)
    

    >>> b.shape
    (3, 3, 3)
    >>> b[:, :, 0]
    array([[1, 1, 1],
           [1, 1, 1],
           [1, 1, 1]], dtype=uint16)
    

提交回复
热议问题