0

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 ?

1
  • 3
    NumPy arrays are homogeneous, there are no mixed type arrays (except object arrays but these are not what I would call recommended!). So the question you need to ask yourself is: what integer value should 'a' or 'b' have? Commented Jul 16, 2017 at 9:21

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.