[英]Is there a good pythonic way to filter dataframe with multiple conditions?
寻找一种进行多条件过滤的有效方法(最好不要遍历每一行)。
原始数据:
fruit price qty comment
apple 1.5 10 In Stock
apple 0.7 20 In Stock
pear 3.0 5 In Stock
pear 2.0 5 In Stock
pear 1.2 30 Out Stock
文件逻辑:
if fruit = 'apple' keep price = 1.5
if fruit = 'Pear' keep qty = 5
预期输出:
fruit price qty comment
apple 1.5 10 In Stock
pear 3.0 5 In Stock
pear 2.0 5 In Stock
您需要使用&
创建布尔型掩码,然后需要'|' 用于两个面罩合并。
m1 = ((df['fruit']=='apple') & (df['price']==1.5))
m2 = ((df['fruit']=='pear') & (df['qty']==5))
df.loc[m1 | m2]
输出:
fruit price qty comment
0 apple 1.5 10 In Stock
2 pear 3.0 5 In Stock
3 pear 2.0 5 In Stock
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.