Monday, November 18, 2024
Google search engine
HomeLanguagesHow to convert 1D array of tuples to 2D Numpy array?

How to convert 1D array of tuples to 2D Numpy array?

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




# importing Numpy
import numpy as np
  
# 1d Array of Tuple
arr = [(1, 2, 3), ('Hi', 'Hello', 'Hey')]
x = map(np.array, arr)
  
# Changing map object to a list, then 
# to an NDarray
x = np.array(list(x))
print(x)
  
# Checking the Dimension of the Resulting
# NDArray
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

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments