使用 .index 删除 pandas 中的行

Dropping rows in pandas with .index

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

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

在 pandas 中使用 drop 时“.index”的用途是什么?

documentation 中所述,您可以将 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

输出:

   A  B   C   D
2  8  9  10  11

在这种情况下,它将删除前 2 行。 在您的示例中使用 .index,您可以找到 Quantity=0 所在的行并检索它们的索引(然后在文档中使用 like)

这是关于 .drop() 方法的详细信息: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html

.drop() 方法需要一个参数 'label' 是索引标签列表(当 axis=0 时,这是默认情况)或列标签(当 axis=1 时). df[df['Quantity'] == 0] returns 一个DataFrame where Quantity=0,但是我们需要的是index label where Quantity=0,所以需要.index。