1

i have the next structured array in 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')])

i need to find in 'col3' the numbers < 179, but also i need to print the row where the number is.

for instance, in matriz the number lower than 179 is 168, then i need to print

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

i did,

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

but i got 168 only the int, any idea?.

and, someone knows, if with pandas library, could i do that?..

thanks

2 Answers 2

1

You can do the following:

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)
Sign up to request clarification or add additional context in comments.

Comments

1
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')]) 

This is a 1d array with 3 fields:

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

We can view one field with:

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

and get a boolean mask of its values:

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

and use that mask to select elements from the whole array:

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

since it is a rec.array, not just a structured array, we can access the field as an attribute as well:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.