使用 .index 在 Pandas 中删除行

son*_*c23 6 python pandas data-science

我遇到了下面的代码行,当其中不存在“.index”时会出现错误。

print(df.drop(df[df['Quantity'] == 0].index).rename(columns={'Weight': 'Weight (oz.)'}))
Run Code Online (Sandbox Code Playgroud)

在熊猫中使用 drop 时“.index”的目的是什么?

Joe*_*Joe 5

由于在解释文件,你可以用dropindex

   A  B   C   D
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11

df.drop([0, 1]) # Here 0 and 1 are the index of the rows
Run Code Online (Sandbox Code Playgroud)

输出:

   A  B   C   D
2  8  9  10  11
Run Code Online (Sandbox Code Playgroud)

在这种情况下,它将删除前 2 行。随着.index你的榜样,您会发现行,其中Quantity=0并检索其索引(然后在文档中使用等)