Casting Transformation to Column in Numpy Array

Viewed 104

I have a table that looks as follows:

City Value
<String> <String>
Chicago 12
Detriot 15
Jersery City 20

This table is locked in this format:

import numpy as np
x = np.array([('Chicago', '12'),('Detriot', '15'),('Jersery City', '20')])

I did some research on Stack Overflow and came to this post here. However I don't know why it is not working. I tried the following code:

x[:,1] = x[:,1].astype(int)

I even tried the following as well and it did not work:

x[:,[1]] = x[:,[1]].astype(int)

However this line when run returns the following:

type(x[0,1])
numpy.str_
1 Answers

Numpy array only support uniform types. Thus, all the items of an array should be of the same type (you can retrieve it using x.dtype), like np.float64 or np.int64 for example.

The type of the items in x cannot change at runtime. x[:,1] = x[:,1].astype(int) performs an implicit conversion so that the types matches. If you need that, then you have to create a new array.

Note that this type can be object. In such a situation, any Python object can be stored in the Numpy array. However, this is generally a bad idea to use object types since they are inefficiently stored in memory, defeat any possible low-level vectorization (ie. slow) and cause performance issues in parallel (because of the GIL).

Note also that Numpy provides structured types to store (quite) complex data structure in each array item.

Related