0

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]
Thanos
  • 2,472
  • 1
  • 16
  • 33
ste_kwr
  • 820
  • 1
  • 5
  • 21

3 Answers3

2

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]
DaveBensonPhillips
  • 3,134
  • 1
  • 20
  • 32
1

a slice works just like a range(), the last argument of a slice is the step value so it tells it to step by a particular number if it is specified. If the other arguments are not specified they return to their defaults

an Example is this:

>>> [1, 2][::]
[1, 2]

which means the whole list, so the last argument just tells python to start from the end of the list and step by a negative of 1 (index positions not numbers)

if they're specified it starts from the end of the slice and steps backwards from there

danidee
  • 9,298
  • 2
  • 35
  • 55
1

The notation of slicing starts with an index and ends with an index. [::-1] works by first looking to the left of the second : and what the first : says is take everything. The -1 then says go backwards so if you imagine you got a line of numbers 1,2,3,4,5,6, the 1 is where you start and you go all the way to the end 6 at that point we just covered the first : now the next part is the -1 it says make your new list by going backwards so 6,5,4,3,2,1 is generated. Hope this is clear.

Seekheart
  • 1,135
  • 7
  • 8