使用视图切片Numpy字符数组

时间:2015-06-24 16:14:38

标签: python numpy

您好我想切片Numpy字符数组以产生以下效果:

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']

我看到你可以将char数组转换成一个矩阵,你可以将其切片,如下所示:

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)

但是,如何将视图矩阵转换回字符数组呢?

1 个答案:

答案 0 :(得分:1)

你去:

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')