ste_kwr ste_kwr - 2 years ago 117
Python Question

Understanding this pandas series slice a[::-1]

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


Answer Source

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 zth 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]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download