我将遵循一个在 Python数据科学手册中找到的示例,该示例的目的是创建两个数组掩码,以最终输出 rainy 天在 summer 中,作者认为夏天从6月21日开始,也就是第172天,到3个月后结束。
在这里,我仅对他进行夏季间隔的那段代码感兴趣:
# Construct a mask for all summer days (June 21st is the 172nd day)
summer = (np.arange((365) - 172 < 90 ) & np.arange((365) - 172 > 0)
在本书的另一个版本中,我找到了这段代码,并且我认为它会导致相同的结果:
# construct a mask of all summer days (June 21st is the 172nd day)
days = np.arange(365)
summer = (days > 172) & (days < 262)
我都不清楚这两个例子,请帮忙。
答案 0 :(得分:0)
也许一个简单的例子有助于更好地理解它。
# sample array
In [19]: week = np.arange(1, 8)
# find middle 3 days of the week
# to do so, we first find boolean masks by performing
# (week > 2) which performs element-wise comparison, so does (week < 6)
# then we simply do a `logical_and` on these two boolean masks
In [20]: middle = (week > 2) & (week < 6)
In [21]: middle
Out[21]: array([False, False, True, True, True, False, False])
# index into the original array to get the days
In [22]: week[middle]
Out[22]: array([3, 4, 5])
&
运算符等效于numpy.logical_and()
,而>
和<
运算符分别等效于numpy.greater()
和numpy.less
。
# create a boolean mask (for days greater than 2)
In [23]: week > 2
Out[23]: array([False, False, True, True, True, True, True])
# create a boolean mask (for days less than 6)
In [24]: week < 6
Out[24]: array([ True, True, True, True, True, False, False])
# perform a `logical_and`; note that this is exactly same as `middle`
In [25]: np.logical_and((week > 2), (week < 6))
Out[25]: array([False, False, True, True, True, False, False])
In [26]: mid = np.logical_and((week > 2), (week < 6))
# sanity check again
In [27]: week[mid]
Out[27]: array([3, 4, 5])