Skip to main content
 首页 » 编程设计

Python:根据位置获取行的索引

2024年10月24日15yxwkf

这是我的 Pandas 数据框

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 

问题一: 如何获取第三行的索引?答案是 12
问题2: 如何删除第三行?

请您参考如下方法:

你可以直接下标到 df 的索引属性中,并将其传递给 drop删除该特定行:

In [98]: 
dframe.index[2] 
 
Out[98]: 
12 

上面显示了类似数组的index对象支持直接使用基于整数定位的下标。

In [99]: 
dframe.drop(dframe.index[2]) 
 
Out[99]: 
    A  B 
10  a  f 
11  b  g 
13  d  i 
14  e  j