Skip to content
Related Articles

Related Articles

Improve Article

Python | Convert Numpy Arrays to Tuples

  • Last Updated : 27 Feb, 2020

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






# 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))

Output:

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

Method #2: Using Naive Approach




# 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))

Output:

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

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :