0

I have a very large numpy array like this. How can I convert this into

array([[1, 1, 0, 0, 1, 0, 0, 1],
       [0, 1, 0, 0, 0, 1, 0, 0],
       [0, 0, 1, 0, 1, 1, 0, 0],
       [0, 0, 1, 0, 1, 1, 0, 0],
       [0, 0, 1, 1, 0, 1, 1, 0],
       [0, 0, 1, 1, 0, 1, 1, 0]])

into this every two rows into one row? Although I need every four rows as one row? This example would be helpful! I searched many places couldn't find a proper solution!

array([[1, 1, 0, 0, 1, 0, 0, 1 , 0, 1, 0, 0, 0, 1, 0, 0],
       [0, 0, 1, 0, 1, 1, 0, 0 , 0, 0, 1, 0, 1, 1, 0, 0],
       [0, 0, 1, 1, 0, 1, 1, 0 , 0, 0, 1, 1, 0, 1, 1, 0]])

and then back again to

array([[1, 1, 0, 0, 1, 0, 0, 1],
       [0, 1, 0, 0, 0, 1, 0, 0],
       [0, 0, 1, 0, 1, 1, 0, 0],
       [0, 0, 1, 0, 1, 1, 0, 0],
       [0, 0, 1, 1, 0, 1, 1, 0],
       [0, 0, 1, 1, 0, 1, 1, 0]])
Xetrov
  • 127
  • 12
poda_badu
  • 159
  • 7

1 Answers1

4

Use .reshape():

>>> import numpy as np
>>> a = np.array([[1, 1, 0, 0, 1, 0, 0, 1],
...        [0, 1, 0, 0, 0, 1, 0, 0],
...        [0, 0, 1, 0, 1, 1, 0, 0],
...        [0, 0, 1, 0, 1, 1, 0, 0],
...        [0, 0, 1, 1, 0, 1, 1, 0],
...        [0, 0, 1, 1, 0, 1, 1, 0]])
>>> b = a.reshape(3,16)
>>> b
array([[1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0],
       [0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0],
       [0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0]])
>>> b.reshape(6,8)
array([[1, 1, 0, 0, 1, 0, 0, 1],
       [0, 1, 0, 0, 0, 1, 0, 0],
       [0, 0, 1, 0, 1, 1, 0, 0],
       [0, 0, 1, 0, 1, 1, 0, 0],
       [0, 0, 1, 1, 0, 1, 1, 0],
       [0, 0, 1, 1, 0, 1, 1, 0]])
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251