# Convert Numpy array with 'n' and 'y' into integer array of 0 and 1

I have a NumPy array of strings: 'n', 'y', wanna convert it into integer array of 0, 1, how to convert it?

imp = SimpleImputer(missing_values=np.nan, strategy='most_frequent')
X = imp.fit_transform(X)

X

array([['n', 'y', 'n', ..., 'y', 'n', 'y'],
['n', 'y', 'n', ..., 'y', 'n', 'y'],
['n', 'y', 'y', ..., 'y', 'n', 'n'],
...,
['n', 'y', 'n', ..., 'y', 'n', 'y'],
['n', 'n', 'n', ..., 'y', 'n', 'y'],
['n', 'y', 'n', ..., 'y', 'n', 'n']], dtype=object)

• What are you trying to do? Can you explain it clearly? – merin Jan 10 '20 at 7:21
• Seems like more of a SO question. – Acccumulation Jan 11 '20 at 7:32

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.

• It should be noted that anything other than 'y' will be converted to 0. 'Y', 'Yes', 'N/A', etc. will all be converted to 0.. – Acccumulation Jan 11 '20 at 7:31

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.

you can use np.where to replace 'n' and 'y'. Please go through the documentation here,

https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html

Also, please try to be more elaborate in your questions such that right solutions can be reached.

You can use np.vectorize as this answer explains:

In [1]: import numpy as np

In [2]: a = np.array([['n', 'y', 'n', 'n', 'y', 'n', 'y'],
...:        ['n', 'y', 'n', 'n', 'y', 'n', 'y'],
...:        ['n', 'y', 'y', 'y', 'y', 'n', 'n']])
...:

In [3]: my_map = {'n': 0, 'y': 1}

In [4]: np.vectorize(my_map.get)(a)
Out[4]:
array([[0, 1, 0, 0, 1, 0, 1],
[0, 1, 0, 0, 1, 0, 1],
[0, 1, 1, 1, 1, 0, 0]])
`