Shamsideen
Shamsideen

Reputation: 11

Merging columns in 2d array in Numpy

How can I merge the 6th and 8th columns of an array in python using hstack? I have tried the code below:

Myarray1 = np.hstack((myarray1 [:, 6:8]))

Upvotes: 1

Views: 189

Answers (2)

joanis
joanis

Reputation: 12229

np.hstack takes a tuple of arrays to stack, so you need to give it the two arrays you want stacked. Your question is not perfectly clear, but I believe you're asking to stack myarray1[:,6] and myarray1[:,8] together.

This will do it for you:

np.hstack((myarray1[:,6], myarray1[:,8]))

The result is a 1-D array with the values of the column 6 followed by the values of column 8 from the original array.

Expanded answer

In the comments, you ask "what about vstach?"

It all depends on what you need to accomplish, so let me give a more detailed example, with a sample input array, and show a few things you can do and what the results would be.

>>> myarray1 = np.array(range(50)).reshape((5,10))
>>> myarray1
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
       [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]])

Create a 1-D array from your two columns with hstack:

>>> np.hstack((myarray1[:,6], myarray1[:,8]))
array([ 6, 16, 26, 36, 46,  8, 18, 28, 38, 48])

Create a 2-D array from your two columns with vstack:

>>> np.vstack((myarray1[:,6], myarray1[:,8]))
array([[ 6, 16, 26, 36, 46],
       [ 8, 18, 28, 38, 48]])

Use @MechanicPig's slice to just extract those two columns and keep them as columns:

>>> myarray1[:, [6,8]]
array([[ 6,  8],
       [16, 18],
       [26, 28],
       [36, 38],
       [46, 48]])

NumPy is confusing at first but very powerful. I recommend carefully working through the NumPy quickstart tutorial to get familiar with all the basic and some not-so-basic matrix manipulations you can do with it. You'll find the time you invest doing so well worth your while.

Upvotes: 1

Mechanic Pig
Mechanic Pig

Reputation: 7736

Stacking is unnecessary, using fancy indices:

>>> myarray1 = np.random.rand(2, 10)
>>> myarray1
array([[0.87904743, 0.13182682, 0.48550022, 0.79578329, 0.66632929,
        0.30420523, 0.6272116 , 0.88457775, 0.34647106, 0.60718063],
       [0.96897505, 0.70569048, 0.7511218 , 0.70031606, 0.21940161,
        0.12380815, 0.47564224, 0.40430928, 0.22397175, 0.00148619]])
>>> myarray1[:, [6, 8]]
array([[0.6272116 , 0.34647106],
       [0.47564224, 0.22397175]])

Upvotes: 1

Related Questions