Home > Back-end >  How to transform numpy array into numpy array of tuples?
How to transform numpy array into numpy array of tuples?

Time:11-04

In Python numpy if I have a numpy array np.array([1,2,3]). How can I transform that into a numpy array [(1,1), (2,4), (3,9)]?

CodePudding user response:

This will work:

list(zip(a, a*a))

CodePudding user response:

This might be a naive approach but it still works.

lst = np.array([1,2,3])
array = []
for i in lst:
    array.append(tuple((i, i*i)))
dt=np.dtype('int,int')
arr = np.array(array,dtype=dt)
print(arr)
print(type(arr))

It will output NumPy array

[(1, 1), (2, 4), (3, 9)]
  • Related