NNInsomniaTonight
NNInsomniaTonight

Reputation: 21

Series is empty when using .loc to slice

I'd like to get the item between Q1 to Q9.

I used .loc to slice the series object:

s.loc['Q1':'Q2']

However it returns a empty series.

Series([], dtype: object)

Normally, I should get a return of

['Q1 ',' Q2 ',' Q3 ',' Q4 ',' Q5 ',' Q6 ',' Q7 ',' Q8 ',' Q9 ']

Q1 to Q9 exist and also they are sequential. I can see them when I run the following

for i in s:
    print(i)
Q1
Q2
Q3
Q4
Q5
Q6
Q7
Q8
Q9
Q10
Q11
Q12
Q13
Q14
Q15

Upvotes: -1

Views: 45

Answers (1)

Scott Boston
Scott Boston

Reputation: 153510

IIUC,

You have s,

s = pd.Series([f'Q{i}' for i in range(1,16)])

Output:

0      Q1
1      Q2
2      Q3
3      Q4
4      Q5
5      Q6
6      Q7
7      Q8
8      Q9
9     Q10
10    Q11
11    Q12
12    Q13
13    Q14
14    Q15
dtype: object

Note the index is a default range index from 0 to 14. If you want to use .loc then you need to change your indexing to match your data.

s.index = s

Output:

Q1      Q1
Q2      Q2
Q3      Q3
Q4      Q4
Q5      Q5
Q6      Q6
Q7      Q7
Q8      Q8
Q9      Q9
Q10    Q10
Q11    Q11
Q12    Q12
Q13    Q13
Q14    Q14
Q15    Q15
dtype: object

Now you can do something like,

s.loc['Q1':'Q9']

Output:

Q1    Q1
Q2    Q2
Q3    Q3
Q4    Q4
Q5    Q5
Q6    Q6
Q7    Q7
Q8    Q8
Q9    Q9
dtype: object

Upvotes: 0

Related Questions