首先我们创建一个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