Home > Net >  How to split a 2d numpy array vertically into a new 2d numpy array?
How to split a 2d numpy array vertically into a new 2d numpy array?

Time:08-17

I have this code that essentially splits a two-dimensional numpy array horizontally and makes a new two-dimensional numpy array out of it.

array1 = np.asarray([[1, 2, 3]])
array2 = np.asarray([[4, 5, 6]])
array3 = np.asarray([[7, 8, 9]])

concatenated = np.concatenate((array1, array2, array3), axis=0)

print(concatenated)

column_split = np.hsplit(concatenated, array1.size)

td_array = []

for array in column_split:
    td_array.append(array.flatten())

print(np.asarray(td_array))

Output of my code:

[[1 2 3]
 [4 5 6]
 [7 8 9]]
[[1 4 7]
 [2 5 8]
 [3 6 9]]

How can I do this with less lines of code? I assume it could be very resource intensive, as soon as I apply this example to my larger task.

CodePudding user response:

I suppose using numpy.hsplit in this case is not necessary and what I am trying to do is covered by the numpy.transpose function.

concatenated = np.concatenate((array1, array2, array3), axis=0)
td_array = concatenated.T

Thank you j1-lee for pointing this out.

  • Related