Python Forum
' List[ Conditional statement ] ' What is this code supposed to do. - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: ' List[ Conditional statement ] ' What is this code supposed to do. (/thread-14447.html)



' List[ Conditional statement ] ' What is this code supposed to do. - Arindam - Nov-30-2018

What does X[y==yi] (Line: 18) do ?

This is the full code:

from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
import numpy as np

iris = load_iris()

X = iris.data[:, [0, 2]]
#print(iris.data)

y = iris.target

def plot_scatter(X,y):
    
    colors = ["red","blue","black","yellow","green","purple","orange"]
    markers = ('s', 'x', 'o', '^', 'v')
    
    for i, yi in enumerate(np.unique(y)):
        Xi = X[y==yi]
        print(Xi)
        plt.scatter(Xi[:,0], Xi[:,1], color=colors[i], marker=markers[i], label=yi) 
   
    plt.xlabel('X label')
    plt.ylabel('Y label')
    plt.legend(loc='upper left')
    
plot_scatter(X,y)



RE: ' List[ Conditional atatement ] ' What is this code supposed to do. - ichabod801 - Nov-30-2018

y == yi evaluates to a boolean value (True or False). But bools are actually a subclass of int, so True = 1 and False = 0. So if y == yi, it selects X[1], and if y != yi it selects X[0].

There was a ternary expression added to Python to avoid this sort of code, so that could be rewritten as:

Xi = X[1] if y == yi else X[0]