Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert numpy scalar to simple python type [duplicate]

Tags:

python

numpy

I have a numpy array with a single value (scalar) which I would like to convert to correspoding Python data type. For example:

import numpy as np
a = np.array(3)
b = np.array('3')

I could convert them to int and str by casting:

a_int = int(a)
b_str = str(b)

but I need to know the types in advance. I would like to convert a to an integer and b to a string without explicit type checking. Is there a simple way to achieve it?

like image 263
btel Avatar asked Apr 24 '13 12:04

btel


People also ask

How do I change the Dtype of a NumPy array?

In order to change the dtype of the given array object, we will use numpy. astype() function. The function takes an argument which is the target data type. The function supports all the generic types and built-in types of data.

How do you repeat a vector in NumPy?

NumPy: repeat() function The repeat() function is used to repeat elements of an array. Input array. The number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis.

What is NumPy scalar type?

In NumPy, a scalar is any object that you put in an array. It's similar to the concept in linear algebra, an element of a field which is used to define a vector space. NumPy ensures all scalars in an array have same types. It's impossible one scalar having type int32, the other scalars having type int64.

How can you shallow copy the data in NumPy view () in method is method or assignments?

copy() is supposed to create a shallow copy of its argument, but when applied to a NumPy array it creates a shallow copy in sense B, i.e. the new array gets its own copy of the data buffer, so changes to one array do not affect the other. x_copy = x. copy() is all you need to make a copy of x .


2 Answers

As described here, use the obj.item() method to get the Python scalar type:

import numpy as np
a = np.array(3).item()
b = np.array('3').item()
print(type(a))  # <class 'int'>
print(type(b))  # <class 'str'>
like image 139
Mike T Avatar answered Sep 28 '22 01:09

Mike T


In this case

import numpy as np
a = np.array(3)
b = np.array('3')
a_int = a.tolist()
b_str = b.tolist()
print type(a_int), type(b_str)

should work

like image 23
YXD Avatar answered Sep 28 '22 03:09

YXD