ramesh ramesh - 7 months ago 20
Python Question

Python: get index of row based on position

Here is my pandas dataframe

In [7]:
dframe = pd.DataFrame({"A":list("abcde"), "B":list("fghij")}, index=[10,11,12,13,14])
dframe

Out[7]:
A B
10 a f
11 b g
12 c h
13 d i
14 e j


Question 1:
How to get index of the third row? Answer is 12

Question 2:
How to delete the third row?

Answer

You can subscript directly into the index attribute of the df, and pass this to drop to remove that specific row:

In [98]:
dframe.index[2]

Out[98]:
12

The above shows that the index object which is array like supports subscripting directly using integer based positioning.

In [99]:
dframe.drop(dframe.index[2])

Out[99]:
    A  B
10  a  f
11  b  g
13  d  i
14  e  j