基于结构数组的Numpy结构数组查询

2024-10-05 14:30:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个如下的结构:

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

使用:

status_type = np.dtype([('area', 'U32'),
                        ('state', 'U32')])

此外,我还有一个product_type数组,比如:

products = np.array([product1, product2, ...], dtype=product_type)

现在我想选择只具有status_type等于('area1', 'active')的产品。我将如何做到这一点。我试过这样的方法:

mask = np.isin(products['area_states'][['area', 'state']],
              ('area1', 'active'))
active_products = products[mask]

不幸的是,这并不是我所希望的那样。当然,我只收到了子数组(status_type)的掩码,但是我更喜欢在产品上得到一个掩码,这样我就可以过滤只有status_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 = '???'

Tags: message产品typestatusnpareaproductproducts
1条回答
网友
1楼 · 发布于 2024-10-05 14:30:43

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

status = np.array(('area1', 'active'), dtype=status_type)

并使用np.any获得活动产品掩码(通过status_type列表沿轴1循环减少)

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,))])

相关问题 更多 >