数组操作:布尔逻辑、花式索引与排序
1. 布尔逻辑与掩码操作
在处理数组时,布尔逻辑和掩码操作是非常强大的工具。首先,我们要注意运算符优先级的问题。例如,下面的表达式如果去掉括号会产生错误:
inches > (0.5 & inches) < 1
我们可以利用逻辑等价关系 A AND B 等价于 NOT (A OR B) 来以不同的方式计算相同的结果:
import numpy as np
# 假设 inches 是一个数组
np.sum(~( (inches <= 0.5) | (inches >= 1) ))
以下是位运算布尔运算符及其等价的通用函数(ufunc)的总结:
| 运算符 | 等价的 ufunc |
| — | — |
| & | np.bitwise_and |
| | | np.bitwise_or |
| ^ | np.bitwise_xor |
| ~ | np.bitwise_not |
利用这些工具,我们可以对气象数据进行各种计算。例如:
print("Number days without rain: ", np.sum(inches == 0))
print("Number days
超级会员免费看
订阅专栏 解锁全文
7

被折叠的 条评论
为什么被折叠?



