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
1.6k views
in Technique[技术] by (71.8m points)

numpy reshape/transpose 3D to wide 2D

Make example

letters = np.array([
    np.array([
        np.array(['a','a','a'])
        , np.array(['b','b','b'])
        , np.array(['c','c','c'])
    ])
    , np.array([
        np.array(['d','d','d'])
        , np.array(['e','e','e'])
        , np.array(['f','f','f'])
    ])
    , np.array([
        np.array(['g','g','g'])
        , np.array(['h','h','h'])
        , np.array(['i','i','i'])
    ])
])
array([[['a', 'a', 'a'],
        ['b', 'b', 'b'],
        ['c', 'c', 'c']],

       [['d', 'd', 'd'],
        ['e', 'e', 'e'],
        ['f', 'f', 'f']],

       [['g', 'g', 'g'],
        ['h', 'h', 'h'],
        ['i', 'i', 'i']]], dtype='<U1')

Desired output

array([['a', 'a', 'a',   'd', 'd', 'd',   'g', 'g', 'g'],
       ['b', 'b', 'b',   'e', 'e', 'e',   'h', 'h', 'h'],
       ['c', 'c', 'c',   'f', 'f', 'f',   'i', 'i', 'i']], dtype='<U1')
  • See how the 2D arrays are now side-by-side?
  • For the sake of memory, I'd prefer to do this with transpose and reshape rather than stacking/ concatting a new array.

Attempt

letters.reshape(
    letters.shape[2],
    letters.shape[0]*letters.shape[1]
)

array([['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'],
       ['d', 'd', 'd', 'e', 'e', 'e', 'f', 'f', 'f'],
       ['g', 'g', 'g', 'h', 'h', 'h', 'i', 'i', 'i']], dtype='<U1')

I think I need to transpose... before reshaping?


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

1 Answer

0 votes
by (71.8m points)
letters.transpose(
    1,0,2
).reshape(
    # where index represents dimension
    letters.shape[2],
    letters.shape[0]*letters.shape[1]
)

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

...