panchester
panchester

Reputation: 327

How to reshape an array with numpy like this:

I have this:

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

And I would like to reshape my array like this:

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

How do I do it using python numpy?

Upvotes: 1

Views: 80

Answers (2)

Divyaansh Bajpai
Divyaansh Bajpai

Reputation: 232

You can simply swap rows after reshaping it.

a= np.array([[0, 0, 1, 1, 2, 2, 3, 3],
       [0, 0, 1, 1, 2, 2, 3, 3]]).reshape(4,4)

a[[1,2]] = a[[2,1]]

Output:

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

Upvotes: 2

akuiper
akuiper

Reputation: 215107

You can just split and concatenate:

a = np.array([[0, 0, 1, 1, 2, 2, 3, 3],
              [0, 0, 1, 1, 2, 2, 3, 3]])

cols = a.shape[1] // 2
np.concatenate((a[:,:cols], a[:,cols:]))

#[[0 0 1 1]
# [0 0 1 1]
# [2 2 3 3]
# [2 2 3 3]]

Upvotes: 2

Related Questions