Python | Convert Numpy Arrays to Tuples

Given a numpy array, write a programm to convert numpy array into tuples.

Examples –

Input: ([[1, 0, 0, 1, 0], [1, 2, 0, 0, 1]])
Output:  ((1, 0, 0, 1, 0), (1, 2, 0, 0, 1))

Input:  ([['manjeet', 'akshat'], ['nikhil', 'akash']])
Output:  (('manjeet', 'akshat'), ('nikhil', 'akash'))

 

Given below are various methods to convert numpy array into tuples.

Method #1: Using tuple and map



filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate
# deletion of columns from numpy array
  
import numpy as np
  
# initialising numpy array
ini_array = np.array([['manjeet', 'akshat'], ['nikhil', 'akash']])
                          
  
# convert numpy arrays into tuples
result = tuple(map(tuple, ini_array))
  
# print result
print ("Resultant Array :"+str(result))

chevron_right


Output:

Result:(('manjeet', 'akshat'), ('nikhil', 'akash'))

Method #2: Using Naive Approach

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate
# deletion of columns from numpy array
  
import numpy as np
  
# initialising numpy array
ini_array = np.array([['manjeet', 'akshat'], ['nikhil', 'akash']])
                          
  
# convert numpy arrays into tuples
result = tuple([tuple(row) for row in ini_array])
  
# print result
print ("Result:"+str(result))

chevron_right


Output:

Result:(('manjeet', 'akshat'), ('nikhil', 'akash'))



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.