ste_kwr - 6 months ago 17

Python Question

Please help me understand how this particular slicing reverses the order of the series. I constantly have trouble understanding slicing using the []. Is there a page that explains it. I think I understand how slicing works with iloc and loc on pandas dataframes. Here is a working exampe

`a=pd.Series(range(0,10))`

a[::-1]

Answer

That's just what it's defined to do!

The syntax `ls[x:y:z]`

means "make a copy of `ls`

, from index `x`

up to index `z`

, taking every `z`

th element"

This makes obvious sense when z is positive:

```
[1,2,3,4,5][::2] -> [1,3,5]
```

(note that defaults for `x`

and `y`

are `0`

and `len(ls)`

)

But negative z is defined to do exactly that:

```
[1,2,3,4,5][::-2] -> [5,3,1]
```

Source (Stackoverflow)

Comments