numpy.astype returns a copy of the array. It does not manipulate your array in-place. So you have to assign the value to a variable:
Y = Y.astype(int)
Answer from Joe on Stack OverflowHello so I want my input to be an integer of 6 numbers โ123456โ but then print them out as 3 arrays with two integer each f.e. โ12โ, โ34โ, โ56โ. Any idea which way is the easiest?
How to convert a float array into integer array? - Python - Data Science Dojo Discussions
python 3.x - How to convert a numpy integer array to an integer - Stack Overflow
python - Convert Numpy array with 'n' and 'y' into integer array of 0 and 1 - Data Science Stack Exchange
How to create an integer array in Python? - Stack Overflow
Videos
numpy.astype returns a copy of the array. It does not manipulate your array in-place. So you have to assign the value to a variable:
Y = Y.astype(int)
Ok, if we have numpy here and something like that:
Y = np.array([5., 0., 4., 1., 9.])
We can convert each element of array to int like this:
map(int, Y)
To get this result:
[5, 0, 4, 1, 9]
It is quite trivial
(X=='y').astype(int)
Should do the trick. It simply converts your array to True or False according to your requirements and then astype will impose the required datatype. By default int will give you 1 for True and 0 for False.
You could use the following code:
X[X=='y'] = 1
X[X=='n'] = 0
This replaces the indexes of 'y' with 1 and of 'n' with 0.
Generally the X=='y' returns a Boolean array which contains True where the 'y' and False everywhere else and so on.
If you are not satisfied with lists (because they can contain anything and take up too much memory) you can use efficient array of integers:
import array
array.array('i')
See here
If you need to initialize it,
a = array.array('i',(0 for i in range(0,10)))
two ways:
x = [0] * 10
x = [0 for i in xrange(10)]
Edit: replaced range by xrange to avoid creating another list.
Also: as many others have noted including Pi and Ben James, this creates a list, not a Python array. While a list is in many cases sufficient and easy enough, for performance critical uses (e.g. when duplicated in thousands of objects) you could look into python arrays. Look up the array module, as explained in the other answers in this thread.