且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何根据在“水果"列中找到的多个值删除所有行?

更新时间:2023-08-28 16:54:28

您需要传递要删除的行的索引,但您传递的是一个布尔数组.您可以将其更改为:

df.drop(df[df.Fruit.isin(["Apple", "Orange"])].index)出去:数量水果价格5 3 香蕉 0.5

或者您可以选择不包含 apple 或 orange 的行:

df[~(df.Fruit.isin(["Apple", "Orange"]))]出去:数量水果价格5 3 香蕉 0.5

I have this simple dataframe

Num   Fruit   Price
1     Apple   1.00
1     Apple   1.00
2     Apple   1.50
2     Orange  1.50
3     Orange  1.00
3     Banana  0.50

I want to drop all the rows which have the fruit Apple or Orange

The expected output should be like this:

Num  Fruit   Price
3    Banana  0.50

I tried to doing the following syntax, but somehow it did not drop all the rows in the dataframe

>>> df.drop(df.Fruit.isin(["Apple","Orange"]))
Fruit Num Price
2   Apple   2  1.50
3  Orange   2  1.50
4  Orange   3  1.00
5  Banana   3  0.50

Any suggestion how to solve this?

You need to pass the indices of the rows to be dropped, but you are passing a boolean array. You can change it to:

df.drop(df[df.Fruit.isin(["Apple", "Orange"])].index)
Out: 
   Num   Fruit  Price
5    3  Banana    0.5

Or you can select the rows that don't contain apple or orange:

df[~(df.Fruit.isin(["Apple", "Orange"]))]
Out: 
   Num   Fruit  Price
5    3  Banana    0.5