5

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?

3
  • Read stackoverflow.com/questions/49751000/… and stackoverflow.com/questions/11309739/… Commented May 21, 2018 at 5:54
  • As a default np.array assigns the best common dtype to the whole array, in this case, a string. Once created that dtype is fixed, and can't be changed by simple assignment. Consider structured arrays or object dtype arrays if you must mix floats and strings. But beware that those come with an increased processing cost. Commented May 21, 2018 at 6:22
  • Since you have a list of tuples, creating a structured array with 3 fields will be relatively easy. Commented May 21, 2018 at 6:27

1 Answer 1

6

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')
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.