How to convert 1D array of tuples to 2D Numpy array?
Last Updated :
18 Mar, 2022
In this article, we will discuss how to convert a 1D array of tuples into a numpy array.
Example:
Input: [(1,2,3),(‘Hi’,’Hello’,’Hey’)]
Output: [[‘1’ ‘2’ ‘3’] [‘Hi’ ‘Hello’ ‘Hey’]] #NDArray
Method 1: Using Map
The map is a function used to execute a function for each item in an Iterable i.e array.
Example:
Here, we first are importing Numpy and defining the 1d Array of Tuples. This Array contains a 0D Array i.e the tuples further using the Map function we are going through each item in the array, and converting them to an NDArray.The map object is being converted to a list array and then to an NDArray and the array is printed further at the last, we are checking that dimension of the resulting Array using the ndim property.
Python3
import numpy as np
arr = [( 1 , 2 , 3 ), ( 'Hi' , 'Hello' , 'Hey' )]
x = map (np.array, arr)
x = np.array( list (x))
print (x)
print (x.ndim)
|
Output:
[['1' '2' '3']
['Hi' 'Hello' 'Hey']]
2
Method 2: The Naive Method
This is a method without using the map or any other function, just basic loops.
Example:
Here, we are defining the 1d Array of Tuples. This Array contains 0D Arrays i.e the tuples and then defines an Empty array further we iterate through each item in ‘arr’ and then we define another empty array for items in each tuple further we also iterate through each item in ‘arrs’ i.e the tuples. Appending each item of the tuple in the ‘items’ array. Appending the ‘items’ array to the ‘x’ array.
Python3
import numpy as np
arr = [( 1 , 2 , 3 ), ( 'Hi' , 'Hello' , 'Hey' )]
x = []
for arrs in arr:
items = []
for item in arrs:
items.append(item)
x.append(items)
x = np.array(x)
print (x)
print (x.ndim)
|
Output:
[[‘1’ ‘2’ ‘3’] [‘Hi’ ‘Hello’ ‘Hey’]]
The Dimension is 2
Share your thoughts in the comments
Please Login to comment...