Python Forum
array replace with 1 when larger than 1
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
array replace with 1 when larger than 1
#1
Dear Python Experts,

I have an array with values of 0 and something above 1.

def af():
    from sklearn.metrics import confusion_matrix
    from sklearn.svm import SVC
    svm = SVC(C=1e9, gamma=1e-07).fit(X_train,y_train)
    svm_predicted_mc = svm.predict(X_test)
    return svm_predicted_mc
af()
Output:
array([0, 0, 0, ..., 1.64, 0, 1.99])

I need to convert it to an array that shows a 0 for every 0 
and a 1 for every value above 1.

I have no idea how to go through the array and convert.
Would appreciate any help.
Reply
#2
I assume these are just numpy arrays so this should work:
>>> a = np.random.randint(0, 5, (5, 5))
>>> a
array([[4, 4, 1, 0, 4],
       [2, 1, 2, 0, 3],
       [1, 1, 0, 2, 4],
       [4, 2, 3, 0, 3],
       [0, 1, 3, 1, 0]])
>>> a > 0
array([[ True,  True,  True, False,  True],
       [ True,  True,  True, False,  True],
       [ True,  True, False,  True,  True],
       [ True,  True,  True, False,  True],
       [False,  True,  True,  True, False]], dtype=bool)
>>> b = a > 0
>>> b.astype(int)
array([[1, 1, 1, 0, 1],
       [1, 1, 1, 0, 1],
       [1, 1, 0, 1, 1],
       [1, 1, 1, 0, 1],
       [0, 1, 1, 1, 0]])
>>>
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python: Returning the most frequently occurring substring in a larger string sskkddrit 2 3,837 Feb-09-2018, 06:41 AM
Last Post: sskkddrit

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020