My apologies if this question has been asked elsewhere; I couldn't find an answer.
I have a pandas series (that is, not a DataFrame) and I want to get the first n values.
Define the series
import numpy as np import pandas as pd my_s = pd.Series(['a', 'b', 'c', np.nan, 'f', 'l', 'd', 'a', 'a', np.nan]) my_s #> 0 a #> 1 b #> 2 c #> 3 NaN #> 4 f #> 5 l #> 6 d #> 7 a #> 8 a #> 9 NaN #> dtype: object
Set n
n = 5
Slice
3.1 With
[:n]
my_s[:n] #> 0 a #> 1 b #> 2 c #> 3 NaN #> 4 f #> dtype: object
3.2 With
.loc[:n]
my_s.loc[:n] #> 0 a #> 1 b #> 2 c #> 3 NaN #> 4 f #> 5 l <~~~~~~~~~ this one is included here but wasn't above #> dtype: object
How come 3.1 and 3.2 return different results? I googled it but could not find any relevant discussion of this.