Python numpy中的条件积

Python numpy中的条件积,python,numpy,Python,Numpy,我有一个列表,它控制数据列表中的哪些项必须相乘 control_list = [1, 0, 1, 1, 0] data_list = [5, 4, 5, 5, 4] 我需要在数据列表中找到控制列表中有1的元素的乘积。我现在的尝试很幼稚,看起来很丑陋 product = 1 for i in range(len(control_list)): if control_list[i]: product *= data_list[i] 我查看了numpy.where()以获

我有一个列表,它控制数据列表中的哪些项必须相乘

control_list = [1, 0, 1, 1, 0]
data_list = [5, 4, 5, 5, 4]
我需要在
数据列表
中找到
控制列表
中有
1
的元素的乘积。我现在的尝试很幼稚,看起来很丑陋

product = 1
for i in range(len(control_list)):
    if control_list[i]: 
        product *= data_list[i]
我查看了
numpy.where()
以获取
data\u列表中所需的元素,但看起来我没有正确获取:

numpy.where(control_list, data_list)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-12-1534a6838544> in <module>()
----> 1 numpy.where(control_list, data_list)

ValueError: either both or neither of x and y should be given
numpy.where(控制列表、数据列表)
---------------------------------------------------------------------------
ValueError回溯(最近一次调用上次)
在()
---->1个数字,其中(控制列表、数据列表)
ValueError:应同时给出x和y或两者都不给出

我的问题是,我能用numpy更有效地实现这一点吗

试试这个。您可以将控件列表转换为布尔值列表,然后使用它索引到数据列表中。然后,您可以使用numpy的乘积函数来获得所有值的乘积

>>> import numpy as np
>>> cList = np.array(control_list, dtype=np.bool)
>>> cList
array([ True, False,  True,  True, False], dtype=bool)
>>> data_list = np.array(data_list)
>>> data_list[cList] # numpy supports fancy indexing
array([5, 5, 5])
>>> np.product(data_list[cList])
125

应该这样做。。。它只是说,在数据列表中的任何位置,只要
control\u list==1

都可以使用产品。首先,这些应该是数组:

control = np.array([1, 0, 1, 1, 0])
data = np.array([5, 4, 5, 5, 4])
现在,我们可以将
控件
转换为布尔掩码:

control.astype(bool)
使用以下选项选择
数据的相应元素

将这些元素乘以:


哇我没想到就这么简单!谢谢:)
control.astype(bool)
data[control.astype(bool)]
product = np.prod(data[control.astype(bool)])