gpt4 book ai didi

python - 基于结构化数组查询 Numpy 结构化数组

转载 作者:行者123 更新时间:2023-12-01 09:06:43 25 4
gpt4 key购买 nike

我有一个如下所示的结构:

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 = '???'

最佳答案

您可以使用

创建目标状态变量
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,))])

关于python - 基于结构化数组查询 Numpy 结构化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51985096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com