Python 基于内部结构化数组查询Numpy结构化数组

Python 基于内部结构化数组查询Numpy结构化数组,python,numpy,indexing,data-science,Python,Numpy,Indexing,Data Science,我有一个如下的结构: product_type = np.dtype([('message_counter', np.int), ('alteration_time', 'U32'), ('area_states', status_type, (3,)), ]) 与: 此外,我还有一个产品类型的数组,如: products = np.array([

我有一个如下的结构:

product_type = np.dtype([('message_counter', np.int),
                         ('alteration_time', 'U32'),
                         ('area_states', status_type, (3,)),
                        ])
与:

此外,我还有一个
产品类型的数组
,如:

products = np.array([product1, product2, ...], dtype=product_type)
现在我想选择的产品只有
状态类型
等于
('area1','active')
。我将如何实现这一点。我试过这样的方法:

mask = np.isin(products['area_states'][['area', 'state']],
              ('area1', 'active'))
active_products = products[mask]
不幸的是,这并没有按照我希望的方式进行。当然,我只收到子阵列的掩码(
status\u type
),但我更喜欢在产品上获得掩码,这样我就可以过滤那些只有
status\u type
('area1','active')
的产品

因此,所有代码都将是以下代码:

status_type = np.dtype([('area', 'U32'),
                        ('state', 'U32')])
product_type = np.dtype([('message_counter', np.int),
                         ('alteration_time', 'U32'),
                         ('area_states', status_type, (3,)),
                         ])
products = np.array([(253, '12:00', [('area1', 'active'), ('area2', 'inactive'), ('area3', 'inactive')]),
                     (254, '13:00', [('area1', 'inactive'), ('area2', 'inactive'), ('area3', 'inactive')])],
                    dtype=product_type)
active_products_in_area1 = '???'

可以使用创建目标状态变量

status = np.array(('area1', 'active'), dtype=status_type)
并使用
np.any
获取活动产品掩码(通过
status\u type
列表沿轴1循环减少)

它只生成示例数组中的第一条记录:

array([(253, '12:00', [('area1', 'active'), ('area2', 'inactive'), ('area3', 'inactive')])],
      dtype=[('message_counter', '<i8'), ('alteration_time', '<U32'), ('area_states', [('area', '<U32'), ('state', '<U32')], (3,))])
数组([(253,'12:00',[('area1','active'),('area2','inactive'),('area3','inactive'))],

dtype=[('message_counter','如果您包含一个示例
产品
数组,那就太好了。
mask = (products['area_states'] == status).any(axis=1)
active_products_in_area1 = products[mask]
array([(253, '12:00', [('area1', 'active'), ('area2', 'inactive'), ('area3', 'inactive')])],
      dtype=[('message_counter', '<i8'), ('alteration_time', '<U32'), ('area_states', [('area', '<U32'), ('state', '<U32')], (3,))])