1

我有一个 numpy 结构化数组。:

myArray = np.array([(1, 1, 1, u'Zone3', 9.223),
        (2, 1, 0, u'Zone2', 17.589),
        (3, 1, 1, u'Zone2', 26.95),
        (4, 0, 1, u'Zone1', 19.367),
        (5, 1, 1, u'Zone1', 4.395)],
         dtype=[('ID', '<i4'), ('Flag1', '<i4'), ('Flag2', '<i4'), ('ZoneName', '<U5'),
                ('Value', '<f8')])

当满足多个条件时,我想对“值”列中的值求和。如果我希望 Flag1 和 Flag2 ==1 我可以使用:

sumResult = (sum(myArray[((myArray["Flag1"] == 1) & (myArray["Flag2"] == 1))]["Value"]))

但是,我还想根据值是否在列表中包含第三个标准,相当于 using x in list

criteriaList = ("Zone1", "Zone2")
sumResult = (sum(myArray[((myArray["Flag1"] == 1) & (myArray["Flag2"] == 1) &
                (myArray["ZoneName"] in criteriaList))]["Value"]))

应该等于 31.345。我是 numpy 的新手,并且已经探索了掩码数组,但不清楚这些是否可以与结构化数组一起使用。谢谢。

4

1 回答 1

1

您需要用于np.in1d测试您的成员资格criteriaList

In [1]: myArray["ZoneName"] in criteriaList
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-1-ff2173ff4348> in <module>()
----> 1 myArray["ZoneName"] in criteriaList

ValueError: The truth value of an array with more than one element is ambiguous.
Use a.any() or a.all()

In [2]: np.in1d(myArray["ZoneName"], criteriaList)
Out[2]: array([False,  True,  True,  True,  True], dtype=bool)

In [3]: myArray[(myArray["Flag1"] == 1) &
   ....:        (myArray["Flag2"] == 1) &
   ....:        np.in1d(myArray["ZoneName"], criteriaList)]["Value"].sum()
Out[3]: 31.344999999999999
于 2015-11-16T20:29:22.410 回答