Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a string numpy array with a number

I have a numpy array

z = array(['Iris-setosa', 'Iris-setosa', 'Iris-setosa', 'Iris-setosa','Iris-versicolor', 'Iris-versicolor', 'Iris-versicolor','Iris-virginica', 'Iris-virginica', 'Iris-virginica'])

I want to replace

Iris-setosa -0
Iris-versicolor - 1
Iris-virginica - 2

to apply logistic regression.

Final output should be like

z = [ 0, 0 ,.. 1,1,.. 2,2,..]

Is there a simple way to do this operation instead of iterating through the array and use replace command?

like image 818
Sanjay Avatar asked Feb 18 '18 14:02

Sanjay


People also ask

How do you replace a string in NUM NumPy?

NumPy String operations: replace() function. numpy.core.defchararray.replace() function. For each element in a given array numpy.core.defchararray.replace() function returns a copy of the string with all occurrences of substring old replaced by new.

How to replace a substring in an array in Python?

The replace () function is used to return a copy of the array of strings or the string, with all occurrences of the old substring replaced by the new substring. This function is very useful if you want to do some changes in the array elements, where you want to replace a substring with some new string value.

How to replace all elements equal to 8 with 20 in NumPy?

The following code shows how to replace all elements in the NumPy array equal to 8 with a new value of 20: #replace all elements equal to 8 with 20 my_array [my_array == 8] = 20 #view updated array print(my_array) [ 4 5 5 7 20 20 9 12]

How to replace NumPy INF values with 0 in Python?

In this Program, we will discuss how to replace numpy.inf values with 0 in Python by using the numpy.where () function. In Python, the inf stands for positive infinity in numpy and it is an infinite number and mostly used for the computation of algorithms.


1 Answers

Use factorize:

a = pd.factorize(z)[0].tolist()
print (a)
[0, 0, 0, 0, 1, 1, 1, 2, 2, 2]

Or numpy.unique:

a = np.unique(z, return_inverse=True)[1].tolist()
print (a)
[0, 0, 0, 0, 1, 1, 1, 2, 2, 2]
like image 120
jezrael Avatar answered Oct 01 '22 20:10

jezrael