Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Question about converting a list of strings to ints

I am trying to convert one column in my numpy array from strings to ints, however when I tried the methods I found online, it didn’t mutate the column. Here is my code:

frequencies = np.array([['a', '24273'],
               ['b', '11416'],
               ['c', '8805'],
               ['d', '6020']])
               frequencies[:, 1] = frequencies[:, 1].astype(int)
               print(frequencies)

The array is unchanged when I print the output.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should assert the datatype for the frequencies array to be dtype=object to accomodate for different data types; ints and strings.

import numpy as np 

frequencies = np.array([['a', '24273'],
               ['b', '11416'],
               ['c', '8805'],
               ['d', '6020']],dtype=object)
frequencies[:, 1] = frequencies[:, 1].astype(int)
print(frequencies)

[['a' 24273]
 ['b' 11416]
 ['c' 8805]
 ['d' 6020]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading