Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
637 views
in Technique[技术] by (71.8m points)

Numpy reshape "2D many columns" to "3D of 2D single columns"

Some sklearn encoders don't accept many-columned 2D arrays.


Make example data

lzt_int = [1, 2, 3, 4, 5, 6]
d1_int = np.array(lzt_int)
d2_int_multi = d2_int.reshape(int(d2_int.shape[0]/3), 3)

A many columned 2D array

>>> d2_int_multi

array([[1, 2, 3],
       [4, 5, 6]])

Want to efficiently turn into a 3D array of 2D single columns that looks like this.

array([
    [[1],
     [4]],

    [[2],
     [5]],

    [[3],
     [6]],
])

Transformation attempts

>>> d2_int_multi.reshape(3, 2, 1, order='C')

array([[[1],
        [2]],

       [[3],
        [4]],

       [[5],
        [6]]])

>>> d2_int_multi.reshape(3, 2, 1, order='F')

array([[[1],
        [5]],

       [[4],
        [3]],

       [[2],
        [6]]])

>>> d2_int_multi.reshape(3, 2, 1, order='A')

array([[[1],
        [2]],

       [[3],
        [4]],

       [[5],
        [6]]])

For the sake of memory - I'd prefer not to access each column, make it a 2D array, before adding it to a 3D array.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You want to add an extra axis and then transpose the result. You can do those operations with this line:

d2_int_multi[None].T

Since this doesn't move any data but only creates a new view of the original array, its very efficient.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...