Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
913 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...