2

lets say I create structured array in numpy:

name = ['Tom' , 'Jim', 'Alice', 'Alice', 'Greg']
height = [188, 160, 160, 157, 180]
pet = ['dog', 'cat', 'fish', 'dog', 'cat']

a = np.zeros(len(name), dtype=[('name', 'U30'), ('height', 'i'), ('pet', 'U30')])

a['name'] = name
a['height'] = height
a['pet'] = pet

Is there a way in numpy to extract those rows which satisfy some condition. For example:

'height' == 160 and 'pet' == 'cat'
3
  • 2
    please next time make sure you put the code there is actually working so that the person who is trying to answer doesn't spend time cleaning it. Like wrapping strings around with ' ' ... Commented Apr 5, 2018 at 19:51
  • 1
    I edited your question to clean up your code so it's runnable. Commented Apr 5, 2018 at 19:57
  • sorry for that , next time I ll check ;] Commented Apr 5, 2018 at 20:06

1 Answer 1

5

IIUC, Here is a way to do it with numpy

a[(a['height'] == 160) & (a['pet'] == 'cat')]

Which returns:

array([('Jim', 160, 'cat')],
      dtype=[('name', '<U30'), ('height', '<i4'), ('pet', '<U30')])

If you want to get just the index at which the conditions are satisfied, use numpy.where:

np.where((a['height'] == 160) & (a['pet'] == 'cat'))
# (array([1]),)

Caveat:

That being said, numpy might not be the best tool for your purposes. To see why, consider what your array a looks like:

>>> a
array([('Tom', 188, 'dog'), ('Jim', 160, 'cat'), ('Alice', 160, 'fish'),
       ('Alice', 157, 'dog'), ('Greg', 180, 'cat')],
      dtype=[('name', '<U30'), ('height', '<i4'), ('pet', '<U30')])

It's kind of hard to read...

Think about using pandas for organizing tabular data:

import pandas as pd
df = pd.DataFrame({'name':name, 'height':height, 'pet':pet})
>>> df

   height   name   pet
0     188    Tom   dog
1     160    Jim   cat
2     160  Alice  fish
3     157  Alice   dog
4     180   Greg   cat

>>> df.loc[(df.height==160) & (df['pet'] == 'cat')]
   height name  pet
1     160  Jim  cat
Sign up to request clarification or add additional context in comments.

1 Comment

If you really need to see it column-wise... not as fancy, but better than adding a whole package, consider ... a.reshape(a.shape[0], 1) for a quick view

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.