Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert singleton array to a scalar value in Python?

Suppose I have 1x1x1x1x... array and wish to convert it to scalar?

How do I do it?

squeeze does not help.

import numpy as np  matrix = np.array([[1]]) s = np.squeeze(matrix) print type(s) print s  matrix = [[1]] print type(s) print s  s = 1 print type(s) print s 
like image 833
Dims Avatar asked Feb 02 '16 15:02

Dims


People also ask

Can only convert an array of size 1 to a python scalar?

This error occurs most often when you attempt to use np.int() to convert a NumPy array of float values to an array of integer values. However, this function only accepts a single value instead of an array of values. Instead, you should use x.

How do you convert a matrix to a scalar in Python?

asscalar() function is used when we want to convert an array of size 1 to its scalar equivalent. Parameters : arr : [ndarray] Input array of size 1.

How do you get a single value from an array in Python?

Using Python's import numpy, the unique elements in the array are also obtained. In the first step convert the list to x=numpy. array(list) and then use numpy. unique(x) function to get the unique values from the list.


1 Answers

You can use the item() function:

import numpy as np  matrix = np.array([[[[7]]]]) print(matrix.item()) 

Output

7 
like image 56
gtlambert Avatar answered Sep 19 '22 13:09

gtlambert