Search code examples
pythonnumpysquare-bracket

What is the meaning of [:, 1:] after np.genfromtxt()?


I am struggeling with python now. i'm trying this script. I am sure this is a very common syntax in python, but it is so generic I can't find any explanation that make sense to me.

Can you help me to understand the meaning of [:, 0] and [:, 1:] in the following lines of code?

syms = np.genfromtxt('people.csv', dtype=str, delimiter=',')[:, 0] 

X = np.genfromtxt('people.csv', dtype=object, delimiter=',')[:, 1:]

people.csv

|       |   |   | |  
|-------|---|---|-|  
|Marc   | .2| -2|A|  
|Martine|-.2|  0|A|  
|Max    | .2| .2|A|  
|Maxine | .2| .1|A|  

Solution

  • That's using slice notation to extract specific rows and columns from the dataset.

    [:, 0] means all rows, column 0.

    [:, 1:] means all rows, columns 1 through n (all columns except 0).

    See Understanding slicing for a good explanation of Python slicing notation.