0

I have a numpy array in this form:

array([['A', 2.2, 9.1],
   ['A', 7.1, 2.3],
   ['B', 4.1, 1.1]],dtype=object)

So I would like to query 'A' and then return all rows and columns with (matching) the string 'A'. Anything not matching the condition is ignored. So the output should be:

form = array([['A', 2.2, 9.1],
              ['A', 7.1, 2.3],dtype=object)

I tried using j = form[np.where(form == 'A')]

which gives array(['A', 'A'], dtype=object). This is not what I want.

Could someone please let me know how I can do this?

1
  • Storing different dtypes in a numpy array is NOT a good idea! A good tool to do things like this would be pandas. Commented May 29, 2018 at 9:10

4 Answers 4

1

You can slice the array when using np.where() so that only this first column is used:

form = np.array([['A', 2.2, 9.1],
   ['A', 7.1, 2.3],
   ['B', 4.1, 1.1]],dtype=object)

j = form[np.where(form[:,0]=='A')]
print (j)
# [['A' 2.2 9.1]
#  ['A' 7.1 2.3]]
Sign up to request clarification or add additional context in comments.

Comments

1

You can avoid using where like so:

form = np.array([['A', 2.2, 9.1],
             ['A', 7.1, 2.3],
             ['B', 4.1, 1.1]])

print(form[form[:,0] == 'A'])

# [['A' 2.2 9.1] 
#  ['A' 7.1 2.3]]

Comments

0

Try creating a list comprehension then in it we iterate trough the length of test then check if 'A' is in the list witch is the element with the index of i:

import numpy as np
test = np.array([['A', 2.2, 9.1],
   ['A', 7.1, 2.3],
   ['B', 4.1, 1.1]],dtype=object)
print(test[[i for i in range(len(test)) if 'A' in test[i]]])

Output:

[['A' 2.2 9.1]
 ['A' 7.1 2.3]]

Comments

0

Quick and dirty way:

import numpy as np
form = np.array([row for row in form_original if row[0] == "A"])

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.