Question about converting a list of strings to ints

Question:

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.

Asked By: imad97

||

Answers:

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]]
Answered By: AboAmmar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.