切片范围

The most robust and consistent way of slicing ranges along arbitrary axes is described in the Selection by Position section detailing the .iloc method. For now, we explain the semantics of slicing using the [] operator.

With Series, the syntax works exactly as with an ndarray, returning a slice of the values and the corresponding labels:

  1. In [31]: s[:5]
  2. Out[31]:
  3. 2000-01-01 0.469112
  4. 2000-01-02 1.212112
  5. 2000-01-03 -0.861849
  6. 2000-01-04 0.721555
  7. 2000-01-05 -0.424972
  8. Freq: D, Name: A, dtype: float64
  9. In [32]: s[::2]
  10. Out[32]:
  11. 2000-01-01 0.469112
  12. 2000-01-03 -0.861849
  13. 2000-01-05 -0.424972
  14. 2000-01-07 0.404705
  15. Freq: 2D, Name: A, dtype: float64
  16. In [33]: s[::-1]
  17. Out[33]:
  18. 2000-01-08 -0.370647
  19. 2000-01-07 0.404705
  20. 2000-01-06 -0.673690
  21. 2000-01-05 -0.424972
  22. 2000-01-04 0.721555
  23. 2000-01-03 -0.861849
  24. 2000-01-02 1.212112
  25. 2000-01-01 0.469112
  26. Freq: -1D, Name: A, dtype: float64

Note that setting works as well:

  1. In [34]: s2 = s.copy()
  2. In [35]: s2[:5] = 0
  3. In [36]: s2
  4. Out[36]:
  5. 2000-01-01 0.000000
  6. 2000-01-02 0.000000
  7. 2000-01-03 0.000000
  8. 2000-01-04 0.000000
  9. 2000-01-05 0.000000
  10. 2000-01-06 -0.673690
  11. 2000-01-07 0.404705
  12. 2000-01-08 -0.370647
  13. Freq: D, Name: A, dtype: float64

With DataFrame, slicing inside of [] slices the rows. This is provided largely as a convenience since it is such a common operation.

  1. In [37]: df[:3]
  2. Out[37]:
  3. A B C D
  4. 2000-01-01 0.469112 -0.282863 -1.509059 -1.135632
  5. 2000-01-02 1.212112 -0.173215 0.119209 -1.044236
  6. 2000-01-03 -0.861849 -2.104569 -0.494929 1.071804
  7. In [38]: df[::-1]
  8. Out[38]:
  9. A B C D
  10. 2000-01-08 -0.370647 -1.157892 -1.344312 0.844885
  11. 2000-01-07 0.404705 0.577046 -1.715002 -1.039268
  12. 2000-01-06 -0.673690 0.113648 -1.478427 0.524988
  13. 2000-01-05 -0.424972 0.567020 0.276232 -1.087401
  14. 2000-01-04 0.721555 -0.706771 -1.039575 0.271860
  15. 2000-01-03 -0.861849 -2.104569 -0.494929 1.071804
  16. 2000-01-02 1.212112 -0.173215 0.119209 -1.044236
  17. 2000-01-01 0.469112 -0.282863 -1.509059 -1.135632