1
import matplotlib.pyplot as plt

plt.scatter(X[:50, 0], X[:50, 1],
            color='red', marker='o', label='setosa')

This code I got from Python Machine Learning. But I don't understand what do X[:50, 0] and X[:50, 1] mean?

I checked about slicing in another SO post. But nowhere they have mentioned the , in the index box.

Sreeraj Chundayil
  • 5,548
  • 3
  • 29
  • 68

2 Answers2

3

The instance[indice] syntax triggers a call for instance.__getitem__ with indice as the argument.

This shortcut allows also the use of the syntax x:y:z to represent slice(x, y, z), which is usually how it is used, but it could be fitted also for other types of indexes, like tuples or strings, as long as your __getitem__ supports these.

In this code it is used as part of numpy's way to slice 2-dimensional arrays, with the tuple containing the slices for each dimensions.


For future reference, you can test with this class:

>>> class sliced:
...     def __getitem__ (self, index):
...             print(index)

>>> d = sliced()

>>> d[:50, 1]
(slice(None, 50, None), 1)

for that particular case, the comma makes the index a tuple (like 1, 2 would if typed in the REPL), whose first item is the :50 which is evaluated as a slice with no start, end at 50 and no step specified (the x:y:z notation fills None in the blanks, and does not require the second :).

Uriel
  • 15,579
  • 6
  • 25
  • 46
0

built-in python list indexing hasn't something like X[:50, 1]. numpy module added this syntax to it's array class. actually this type of indexing introduced in MATLAB. see here for more information

Alireza Afzal Aghaei
  • 1,184
  • 10
  • 27