首先我们创建一个dataframe:

import pandas as pd
fruit_list = [ ('Orange', 34, 'Yes' ) ,
             ('Mango', 24, 'No' ) ,
             ('banana', 14, 'No' ) ,
             ('Apple', 44, 'Yes' ) ,
             ('Pineapple', 64, 'No') ,
             ('Kiwi', 84, 'Yes')  ]
  

df = pd.DataFrame(fruit_list, columns = ['Name' , 'Price', 'Stock']) 

此时生成的dataframe如下:

	Name	Price	Stock
0	Orange	34	Yes
1	Mango	24	No
2	banana	14	No
3	Apple	44	Yes
4	Pineapple	64	No
5	Kiwi	84	Yes

根据列Stock中值是否为True对行数据进行删除:

indexNames=df[df['Stock']=='No'].index
df.drop(indexNames,inplace=True)

此时df变为:

	Name	Price	Stock
0	Orange	34	Yes
3	Apple	44	Yes
5	Kiwi	84	Yes

我们也可以通过在df.drop方法中使用.loc来获得类似的结果

df.drop(df.loc[df['Stock']=='Yes'].index, inplace=True)

此时df变为

	Name	Price	Stock
1	Mango	24	No
2	banana	14	No
4	Pineapple	64	No

上面的例子仅有一个限定条件,我们还可以基于多个限定条件删除行,例如在上面的dataframe中,我们可以删除价格大于30和价格小于70的行:

indexNames=df[(df['Price']>=30)&(df['Price']<=70)].index
df.drop(indexNames,inplace=True)

此时df变为:

	Name	Price	Stock
1	Mango	24	No
2	banana	14	No
5	Kiwi	84	Yes

bool masking是基于列值删除dataframe中的行的最好,最简单的方法

同样我们基于如下的dataframe:

	Name	Price	Stock
0	Orange	34	Yes
1	Mango	24	No
2	banana	14	No
3	Apple	44	Yes
4	Pineapple	64	No
5	Ki

接下来我们利用bool masking

print(df[df.Price > 40])
print('............................')
print(df[(df.Price > 40) & (df.Stock== 'Yes')])  

输出:

        Name  Price Stock
3      Apple     44   Yes
4  Pineapple     64    No
5       Kiwi     84   Yes
............................
    Name  Price Stock
3  Apple     44   Yes
5   Kiwi     84   Yes
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐