简体   繁体   中英

Python Numpy array assignment casting int

I'm fairly new with numpy.

As shown below, when I try to cast the numeric values from strings to integers, it doesn't seem to 'stick', as below:

>> import numpy as np
>>> a = np.array([['a','1','2'],['b','3','4']])
>>> a[:,1:3].astype(int)
array([[1, 2],
       [3, 4]])
>>> a[:,1:3] = a[:,1:3].astype(int)
>>> a
array([['a', '1', '2'],
       ['b', '3', '4']],
      dtype='<U1')

How can I convert the string values to ints in the array ?

You need to first change the dtype of the full array to object in order for it to contain both strings and integers:

a = a.astype(object)
a[:,1:3] = a[:,1:3].astype(int)
print(a)
> [['a' 1 2]
   ['b' 3 4]]

Though note that better solutions may exist, for example using pandas , using columns of different types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM