Home > front end >  Question about converting a list of strings to ints
Question about converting a list of strings to ints

Time:09-26

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.

CodePudding user response:

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]]
  • Related