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?
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.
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.
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]
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With