I have a set of values
y_train=["User","Bot","User","Bot",.......]
y_pred=["Bot","User","User","Bot".........]
I want to generate an array which returns 1 if the values of y_train[i] and t_pred[i] dont match.Both y_train and y_pred consist of same no of values
That is array indicator should be:
indicator=[1,1,0,0..........]
I have tried
indicator=0
for i in range(len(y_train)):
if y_train[i]!=y_pred[i]:
indicator[i]=1
else:
indicator[i]=0
But error being shown is :
'int' object does not support item assignment
How could this be done? Thanks
4 Answers 4
indicator = map(lambda x,y: int(x != y), y_train, y_pred)
As commented, if indicator serves as a boolean array, you may remove the int conversion to generate a True & False array:
indicator = map(lambda x,y: x != y, y_train, y_pred)
or as suggested in the comment:
indicator = map(operator.ne, y_train, y_pred)
indicator = [t != p for t, p in zip(y_train, y_pred)]
2 Comments
You have declared indicator as an int. Try this:
indicator=[]
for i in range(len(y_train)):
if y_train[i]!=y_pred[i]:
indicator.append(1)
else:
indicator.append(0)
Another way to do this is:
indicator = []
for i,j in zip(y_train,y_pred):
if i==j:
indicator.append(0)
else:
indicator.append(1)
Comments
First, this is what you should do:
indicator = [1 if x != y else 0 for x, y in zip(y_train, y_pred)]
# or indicator = [int(x != y) for x, y in zip(y_train, y_pred)]
This is a list comprehension. It uses zip to go over the values of y_train and y_pred in parallel. For every pair of corresponding values in y_train and y_pred, indicator contains 1 if the values are unequal and 0 otherwise.
Now, here's what's wrong with your attempt. First, if you want indicator to be a list, don't make it an int:
#indicator=0
indicator = []
Second, you can't assign to indices past the end of a list. You can append the values instead:
for i in range(len(y_train)):
if y_train[i]!=y_pred[i]:
# indicator[i]=1
indicator.append(1)
else:
# indicator[i]=0
indicator.append(0)