Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert dtype of a specific column in a numpy array [duplicate]

I want change the numpy column data type, but when I to replace the original numpy column, the dtype will not change succesfully.

import numpy as np 

arraylist =[(1526869384.273246, 0, 'a0'),
(1526869385.273246, 1, 'a1'),
(1526869386.273246, 2, 'a2'),
(1526869387.273246, 3, 'a3'),
(1526869388.273246, 4, 'a4'),
(1526869389.273246, 5, 'a5'),
(1526869390.273246, 6, 'a6'),
(1526869391.273246, 7, 'a7'),
(1526869392.273246, 8, 'a8'),
(1526869393.273246, 9, 'a9'),
(1526869384.273246, 0, 'a0'),
(1526869385.273246, 1, 'a1'),
(1526869386.273246, 2, 'a2'),
(1526869387.273246, 3, 'a3'),
(1526869388.273246, 4, 'a4'),
(1526869389.273246, 5, 'a5'),
(1526869390.273246, 6, 'a6'),
(1526869391.273246, 7, 'a7'),
(1526869392.273246, 8, 'a8'),
(1526869393.273246, 9, 'a9')]

array =  np.array(arraylist)

array.dtype

dtype('<U32')

array[:,0]=array[:,0].astype("float64")
array[:,0].dtype 

>>> dtype('<U32') 

Event through I changed the dtype of the column, but why I want to replace the orignal column it's still u32?

like image 351
nooper Avatar asked May 21 '18 05:05

nooper


People also ask

How do I change the datatype of a column in 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.

How do you duplicate an element in an array in NumPy?

Python Numpy – Duplicate or Copy Array Copying array means, a new instance is created, and the contents of the original array is copied into this array. To copy array data to another using Python Numpy library, you can use numpy. ndarray. copy() function.

How do I print a specific column in NumPy?

Access the ith column of a Numpy array using transposeTranspose of the given array using the . T property and pass the index as a slicing index to print the array.

How do you change the datatype of an array in Python?

We have a method called astype(data_type) to change the data type of a numpy array. If we have a numpy array of type float64, then we can change it to int32 by giving the data type to the astype() method of numpy array. We can check the type of numpy array using the dtype class.


1 Answers

If you're okay with named columns, you can define a tuple of dtypes and assign them to array during creation:

dtype = [('A', 'float'), ('B', 'int'), ('C', '<U32')]
array = np.array(arraylist, dtype=dtype)

array['A'].dtype  # note, array[: 0] does not work here since these are named columns
dtype('float64')
like image 167
cs95 Avatar answered Sep 21 '22 12:09

cs95