简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM