ibredfish
ibredfish

Reputation: 141

How to find a 'str' in a 2-D array and return element in next column?

I've successfully combined two lists (A, B) using numpy.array and assigned it to a new variable. The first list contained strings (A) and the second contained integers (B). When I print the new variable (C) I get:

    [[Str, Str]
     [Int, Int]]

I'm now trying to find the corresponding integer if the str == 'XYZ'. How do I use the index function to find the int in the row next to 'XYZ'?

My initial thought was to assign the new list to a variabe i.e. D:

  D = C[A == 'XYZ',]

However, I only get True, False, etc.

Sorry, I know this is quite basic.

Upvotes: 0

Views: 40

Answers (2)

ibredfish
ibredfish

Reputation: 141

Here's what I came up with:

  import numpy as np 
  A = ['ABC', 'XYZ']
  B = [1, 99]
  C = B[A == 'ABC']
  D = B[A != 'ABC']
  print(C)
  print(B)

Upvotes: 0

mathew gunther
mathew gunther

Reputation: 180

Is this what you're trying to accomplish?

import numpy as np my_matrix = np.array([['ABC','XYZ'],[1,99]]) print(my_matrix) my_index = my_matrix[0]=='XYZ' print(my_matrix[1][my_index])

Upvotes: 2

Related Questions