简体   繁体   中英

Merge two 2D numpy.ndarray

I am trying to merge two 2D numpy arrays - using np.concatenate . This is my code:

import numpy as np

arr = np.array([[]]) #empty 2D array for result
a = np.array([[0.0012, 0.032, 0.039, 0.324]])
b = np.array([[1, 0.2, 0.03039, 0.1324]])
arr = np.concatenate(arr, a, axis=0)
arr = np.concatenate(arr, b, axis=0)
print(arr)

I also tried:

np.concatenate(arr, a, axis=0)
np.concatenate(arr, b, axis=0)

Or:

arr = np.concatenate(a, b, axis=0)

But It throws error at arr = np.concatenate(arr, a, axis=0) line. Error: TypeError: only integer scalar arrays can be converted to a scalar index

Any possible solution? I want have this result: arr = np.array([[0.0012, 0.032, 0.039, 0.324], [1, 0.2, 0.03039, 0.1324]])

You can use hstack and vstack functions for it. Note, that vstack needs your arrays to have equal x-dimensions.

arr = np.hstack([arr, a])
arr = np.vstack([arr, b])

If you want to use concatenate function, you should pass the list of arrays as the first argument:

arr = np.concatenate([arr, b], axis=0)

This usage needs to have equal x-dimensions too.

You can also use the block function for complicated concatenation.

How about this:

import numpy as np
a = np.array([[0.0012, 0.032, 0.039, 0.324]])
b = np.array([[1, 0.2, 0.03039, 0.1324]])

result = np.concatenate([a, b], axis=0)

print (result)

That gives:

[[ 0.0012   0.032    0.039    0.324  ]
 [ 1.       0.2      0.03039  0.1324 ]]

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