Slice rows with same index number pandas

Viewed 161

So i have this dataframe that has same index number for a reason. when i am trying to slice the select rows using the code below i get the error.

df = pd.read_excel('18nov.xlsx')
df = pd.DataFrame(df)
df = df.loc[120:140]

KeyError: 'Cannot get left slice bound for non-unique label

Dataframe i have in my excel file

      Name    Age       Time
100   Tom     20       01:00
110   nick    21       01:00
120   krish   19       01:00
130   jack    18       01:00
140   Rick    26       01:00
150   John    23       01:00       
100   Tom     20       01:10
110   nick    21       01:10
120   krish   19       01:10
130   jack    18       01:10
140   Rick    26       01:10
150   John    23       01:10
100   Tom     20       01:20
110   nick    21       01:20
120   krish   19       01:20
130   jack    18       01:20
140   Rick    26       01:20
150   John    23       01:20

What i want when i slice using index number

      Name    Age       Time
120   krish   19       01:00
130   jack    18       01:00
140   Rick    26       01:00
120   krish   19       01:10
130   jack    18       01:10
140   Rick    26       01:10
120   krish   19       01:20
130   jack    18       01:20
140   Rick    26       01:20

Thank you in advance .

2 Answers

You are getting error as their are duplicate entries. But you can achieve your desired result by trying this code.

desired_df=df[(df.index>=120)&(df.index<=140)]
print(desired_df)

      Name    Age       Time
120   krish   19       01:00
130   jack    18       01:00
140   Rick    26       01:00
120   krish   19       01:10
130   jack    18       01:10
140   Rick    26       01:10
120   krish   19       01:20
130   jack    18       01:20
140   Rick    26       01:20

Use DataFrame.query here:

df = df.query('120 <= index <= 140')
print (df)
      Name  Age   Time
120  krish   19  01:00
130   jack   18  01:00
140   Rick   26  01:00
120  krish   19  01:10
130   jack   18  01:10
140   Rick   26  01:10
120  krish   19  01:20
130   jack   18  01:20
140   Rick   26  01:20
Related