joshlk
joshlk

Reputation: 1651

Slice Numpy character array using a view

Hi I would like to slice a Numpy character array to have the following effect:

a = np.array(['2014-04-02', '2015-06-01', '1990-03-31'], dtype='|S11')
a[:, (0, 1, 2, 3, 5, 6, 8, 9)]
['20140402', '20150601', '19900331']

Iv seen that you can convert the char array into a matrix which you can then slice, like so:

view = a.view(np.uint8).reshape(a.shape + (a.dtype.itemsize,))
view_slice = view[:, (0, 1, 2, 3, 5, 6, 8, 9)]
view_slice ([[50, 48, 52, 45, 52, 45, 50,  0],
             [50, 48, 53, 45, 54, 45, 49,  0],
             [49, 57, 48, 45, 51, 45, 49,  0]], dtype=uint8)

But then how do I convert the view matrix back into a character array?

Upvotes: 2

Views: 295

Answers (1)

Thomas Leonard
Thomas Leonard

Reputation: 1047

here you go :

view_slice = view[:, (0, 1, 2, 3, 5, 6, 8, 9)] # your slicing was not correct
view_slice.ravel().view(np.dtype('|S8'))
# array(['20140402', '20150601', '19900331'], dtype='|S8')

Upvotes: 1

Related Questions