简体   繁体   English

理解python和numpy语法来屏蔽和过滤数组

[英]Understanding python & numpy syntax to mask and filter array

Please help me understand how the lines below are working.请帮助我了解以下几行的工作方式。

  1. How does a pair of parentheses create an array and then individual elements go through logical condition check and create a new array?一对括号如何创建一个数组,然后单个元素通过逻辑条件检查并创建一个新数组?

  2. How does condition in square brackets filter elements create another sub-array?方括号中的条件过滤元素如何创建另一个子数组?

     import numpy as np my_vector=np.array([-17, 4, 0, 2, 21, 37, 105]) array([-17, 4, 0, 2, 21, 37, 105]) zero_mod_7_mask= 0 == (my_vector % 7) #question 1 array([False, False, True, False, True, False, True]) my_subarray = my_vector[zero_mod_7_mask] # question 2 array([ 0, 21, 105])
  1. The parentheses do nothing but ensure that what's inside of them is done first括号什么也不做,只是确保首先完成其中的内容

  2. The array just keeps the True elements数组只保留True元素

In a ipython interactive session:ipython交互式会话中:

In [230]: my_vector=np.array([-17, 4, 0, 2, 21, 37, 105])

The modulus calculation:模数计算:

In [231]: my_vector%7                                                           
Out[231]: array([4, 4, 0, 2, 0, 2, 0])

identifying elements of that which are 0:识别 0 的元素:

In [232]: 0 == my_vector%7                                                      
Out[232]: array([False, False,  True, False,  True, False,  True])

Indexes of those True elements:这些True元素的索引:

In [233]: np.nonzero(_)                                                         
Out[233]: (array([2, 4, 6]),)

Selecting those elements from my_vector :my_vector选择这些元素:

In [234]: my_vector[_]                                                          
Out[234]: array([  0,  21, 105])

Doing the same with the boolean array:对布尔数组做同样的事情:

In [235]: my_vector[Out[232]]                                                   
Out[235]: array([  0,  21, 105])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM