Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change data type of a array in python

Tags:

python

numpy

I have created a array by generating a group of random numbers and converted them into int type. However, i do not think my way below is efficient. Is there a best way to change the data type in a array?

# standard normal distributed random numbers
c=random.randn(5,5)
c

array([[-0.37644781, -0.81347483, -0.36895952, -2.68702544, -0.96780752],
   [ 0.05293328,  1.65260753,  0.55586611, -0.5786392 ,  0.50865003],
   [ 1.25508358,  0.51783276,  2.36435212, -0.23484705, -1.20999296],
   [ 2.07552172,  0.65506648,  0.10231436, -0.26046045,  0.40148111],
   [ 0.24864496, -1.8852587 , -2.51091886,  1.01106003,  1.53118353]])

d=array([[-0.37644781, -0.81347483, -0.36895952, -2.68702544, -0.96780752],
       [ 0.05293328,  1.65260753,  0.55586611, -0.5786392 ,  0.50865003],
       [ 1.25508358,  0.51783276,  2.36435212, -0.23484705, -1.20999296],
       [ 2.07552172,  0.65506648,  0.10231436, -0.26046045,  0.40148111],
       [ 0.24864496, -1.8852587 , -2.51091886,  1.01106003,  1.53118353]],dtype=int)

d
array([[ 0,  0,  0, -2,  0],
       [ 0,  1,  0,  0,  0],
       [ 1,  0,  2,  0, -1],
       [ 2,  0,  0,  0,  0],
       [ 0, -1, -2,  1,  1]])
like image 758
Michael Ji Avatar asked Apr 24 '15 10:04

Michael Ji


People also ask

Can you change the data type of an array?

Converting Data Type on Existing Arrays The best way to change the data type of an existing array, is to make a copy of the array with the astype() method.

Can you have different data types in an array Python?

You can create an array with elements of different data types when declare the array as Object. Since System. Object is the base class of all other types, an item in an array of Objects can have a reference to any other type of object.

What is the data type of array in Python?

Python's array module provides space-efficient storage of basic C-style data types like bytes, 32-bit integers, floating point numbers, and so on. Arrays created with the array. array class are mutable and behave similarly to lists—except they are “typed arrays” constrained to a single data type.

Can you modify a numpy array?

Reshape. There are different ways to change the dimension of an array. Reshape function is commonly used to modify the shape and thus the dimension of an array.


1 Answers

Either you find a way to get the output with the correct type or you use astype, see the docs, in order to change the type of an array

In your case the following example gives you an array of type np.int

c=random.randn(5,5).astype(np.int)
like image 110
plonser Avatar answered Oct 17 '22 05:10

plonser