[英]What does the equivalence operator mean when used in a numpy array
I am following an example which I found it in the Python Data science handbook , the purpose of this example is to create two array masks to finally output the rainy days in summer , the author supposed that summer starts on 21st June which is the 172th day and it ends 3 months later. 我跟随一个在Python数据科学手册中找到的示例,该示例的目的是创建两个数组蒙版,以最终输出夏天的雨天 ,作者认为夏天始于6月21日,即第172天并在3个月后结束。
Here I am only interested in only the piece of code where he made the summer interval: 在这里,我只对他进行夏季间隔的那段代码感兴趣:
# Construct a mask for all summer days (June 21st is the 172nd day)
summer = (np.arange((365) - 172 < 90 ) & np.arange((365) - 172 > 0)
In another version of the book, I found this code, and I think it leads to the same result: 在本书的另一个版本中,我找到了以下代码,并且我认为它会导致相同的结果:
# construct a mask of all summer days (June 21st is the 172nd day)
days = np.arange(365)
summer = (days > 172) & (days < 262)
Both examples are not clear to me, please help. 我都不清楚这两个例子,请帮忙。
Maybe a simple example would help to understand it better. 也许一个简单的例子将有助于更好地理解它。
# 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])
the &
operator is equivalent to numpy.logical_and()
whereas the >
and <
operators are equivalent to numpy.greater()
and numpy.less
respectively. &
运算符等效于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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.