-2

What is the main difference between df[:] and df[::] and could you please give me one sample example for regarding this.i was unable to understand.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
amigana _34
  • 35
  • 1
  • 1
  • 8

2 Answers2

0

Assuming you are talking about python lists and not pandas dataframes:

Consider a list l:

In [301]: l = range(20,30)

In [302]: l
Out[302]: [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

So, if you do something like :

In [303]: l[3:6]
Out[303]: [23, 24, 25]

This means, you want to extract a list of elements from l from index=3 to index=6(6 not included). So, it returned 23 which is l[3], 24 which is l[4] and 25 which is l[5].

Note: 26(l[6]) was not returned as 6 is not included in l[3:6]

So, l[:] -- Would return the all the elements as no range was specified.

In [305]: l[:]
Out[305]: [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

For extended slicing:

l[1:6:2] -- Would mean, you want elements from index=1 to index=6 with a step of 2. Step=2 means, increment every index by 2

So, you should get below elements:
 l[1], 
 l[1 + 2](because the step we defined is 2), 
 l[1 + 2 + 2]( keep adding `2` to the previous index )

Now, previous index here is 5 and the limit we gave was 6 where 6 is not included. Hence, we get only 3 elements as mentioned above. Check below:

In [307]: l[1:6:2]
Out[307]: [21, 23, 25]

So, l[::] would also return the entire list, as we haven;t specified any range here.

In [309]: l[::]
Out[309]: [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

You would need to practice slicing of strings in python to get a hang of it.

Let me know if this helps.

Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
0

There is no difference.

sequence[start:end:step]
sequence[start:end]

':' and '::' represent slices of sequences. If start, end and/or step are omitted, then the defaults are used instead: 0 is the default for start, len(sequence) is the default for end, and 1 is the default for step.

So if, df = [1,2,3,4,5,6,7,8] then,

[df[::]==df[:], df[:] == df[0: len(df): 1], df[::] == df[0: len(df): 1]]

Outputs: [True, True, True]