Python Forum

Full Version: how to join by stack multiple types in numpy arrays
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
import numpy as np

arr1 = np.array([1, 2, 3, 4, 5, 6, 7])
arr2 = np.array(['n', 'b', 'c', 'y', 'f', 'j', 'p'])

l = np.stack((arr1, arr2), axis=1)
print(l)
the output is:
[['1','n'] ['2', 'b'] ['3','c'] ['4','y']['5','f'] ['6','j'] ['7','p']]

i would like that the types will be like the input so that the output will be:
[[1,'n'] [2, 'b'] [3,'c'] [4,'y'][ 5,'f'] [6,'j'] [7,'p']]
numpy arrays have a data type. All elements in the array are that type. You cannot make a numpy array that has strings and integers.

That said, you can have a numpy array of structures.
import numpy as np
from numpy.lib import recfunctions

arr1 = np.array([1, 2, 3, 4, 5, 6, 7])
arr2 = np.array(["n", "b", "c", "y", "f", "j", "p"])

l = recfunctions.merge_arrays((arr1, arr2))
print(l)
Output:
[(1, 'n') (2, 'b') (3, 'c') (4, 'y') (5, 'f') (6, 'j') (7, 'p')]