Home > Mobile >  Using the original index after slicing a df
Using the original index after slicing a df

Time:06-14

Suppose I have a dataframe dataset as the following:

dataset = pd.DataFrame({'id':list('123456'),
                       'B':[4,5,4,5,5,4],
                        'C':[7,8,9,4,2,3]})
print(dataset)

  id  B  C
0  1  4  7
1  2  5  8
2  3  4  9
3  4  5  4
4  5  5  2
5  6  4  3

Now I slice it using iloc() and get

dataset = dataset.iloc[2:5]

  id  B  C
2  3  4  9
3  4  5  4
4  5  5  2

Now I set the id as the new index due to my needs in my project, so I do

dataset.set_index("id", inplace=True)
print(dataset)

    B  C
id      
3   4  9
4   5  4
5   5  2

I would like to select the new dataset using iloc on the original index. So if I do dataset.iloc[3] I would lke to see the first row. However, if I do that it throws me a out of bound error. If I do dataset.iloc[0] it gives me the first row.

Is there anyway I can preserve the original index? Thanks.

CodePudding user response:

iloc is slice by its position you can check subtract the lower

n = 2 # n is 2 since you slice 2:5
dataset.iloc[3-n-1]
Out[648]: 
B    4
C    9
Name: 3, dtype: int64

CodePudding user response:

In this case it is recommended to use loc instead of iloc:

dataset.index = dataset.index.astype('int')
dataset.loc[3]
>>>
B    4
C    9
Name: 3, dtype: int64
  • Related