打印numpy结构化数组中数据的行

2024-09-27 21:34:15 发布

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

下一个结构数组是numpy:

>>> matriz
rec.array([('b8:27:eb:07:65:ad', '0.130s', 255), 
          ('b8:27:eb:07:65:ad', '0.120s', 215), 
          ('b8:27:eb:07:65:ad', '0.130s', 168) ],
  dtype=[('col1', '<U17'), ('col2', '<U17'), ('col3', '<i4'), 
   ('col4','<U17')])

我需要在'col3'中找到数字<;179,但我还需要打印数字所在的行

例如,在matriz中,小于179的数字是168,那么我需要打印

('b8:27:eb:07:65:ad', '0.130s', 168)

是的

for j in matriz['col3']:
         if j< 254:
                   print(j)

但是我只得到了int,知道吗

有人知道,如果有熊猫图书馆,我能做到吗

谢谢


Tags: numpy数字数组结构arrayadcol2col3
2条回答
In [128]: arr=np.rec.array([('b8:27:eb:07:65:ad', '0.130s', 255), 
     ...:           ('b8:27:eb:07:65:ad', '0.120s', 215), 
     ...:           ('b8:27:eb:07:65:ad', '0.130s', 168) ],
     ...:   dtype=[('col1', '<U17'), ('col2', '<U17'), ('col3', '<i4')]) 

这是一个1d数组,包含3个字段:

In [129]: arr
Out[129]: 
rec.array([('b8:27:eb:07:65:ad', '0.130s', 255),
           ('b8:27:eb:07:65:ad', '0.120s', 215),
           ('b8:27:eb:07:65:ad', '0.130s', 168)],
          dtype=[('col1', '<U17'), ('col2', '<U17'), ('col3', '<i4')])

我们可以通过以下方式查看一个字段:

In [130]: arr['col3']
Out[130]: array([255, 215, 168], dtype=int32)

并获取其值的布尔掩码:

In [131]: arr['col3']<179
Out[131]: array([False, False,  True])

并使用该遮罩从整个数组中选择元素:

In [132]: arr[arr['col3']<179]
Out[132]: 
rec.array([('b8:27:eb:07:65:ad', '0.130s', 168)],
          dtype=[('col1', '<U17'), ('col2', '<U17'), ('col3', '<i4')])

由于它是一个rec.array,而不仅仅是一个结构化数组,因此我们还可以将字段作为属性进行访问:

In [135]: print(arr[arr.col3<254])
[('b8:27:eb:07:65:ad', '0.120s', 215) ('b8:27:eb:07:65:ad', '0.130s', 168)]

您可以执行以下操作:

matrix = np.array([('b8:27:eb:07:65:ad', '0.130s', 255),
                   ('b8:27:eb:07:65:ad', '0.120s', 215),
                   ('b8:27:eb:07:65:ad', '0.130s', 168)],
                  dtype=[('col1', '<U17'), 
                         ('col2', '<U17'), 
                         ('col3', '<i4')])

for row in matrix:
    if row['col3'] < 254:
        print(row)

相关问题 更多 >

    热门问题