Learning from masters
Learning from masters

Reputation: 2782

Select from a 2D list all rows where a column has a desired value

I have a 2D list of MxN elements. I want to have all those rows where the column j has a certain value. My idea is to do:

my_2D_list = np.transpose(np.array(my_2D_list))
temp = my_2D_list[my_2D_list[j] == myvalue]

but temp is empty. If I print my_2D_list I can see the array is transposed, but it is like:

 [['0' '0' '0' ... '0' '0' '0']
  ['0' '0' '1' ... '75' '80' '80'] 
  ['60' '60' '0' ... '10' '108' '108']  ...

without the commas between columns, so I guess it is not splitting each row in columns in the new matrix, but is kind of a continuum... how can I fix this?

Upvotes: 0

Views: 1286

Answers (1)

MkWTF
MkWTF

Reputation: 1372

For you to select the values from a column in a matrix you have to do it like this:

list[row_idx, col_idx]

where the first argument to the index is the row index, and the second argument is the column index. You can check the docs in here.

In your case, this would look like this: my_2D_list[:, j]. Here is a full example for you to check:

j = 2
n = 1

np.random.seed(42)
my_2D_list = np.random.randint(0, 3, 100).reshape((10, 10))

print(">>> Whole matrix\n%s" % my_2D_list)
print("\n>>> Column %d\n%s" % (j, my_2D_list[:,j]))
print("\n>>> Rows where column %d == %d \n%s" % (j, n, my_2D_list[my_2D_list[:,j] == n]))

Output:

>>> Whole matrix
[[2 0 2 2 0 0 2 1 2 2]
 [2 2 0 2 1 0 1 1 1 1]
 [0 0 1 1 0 0 0 2 2 2]
 [1 2 1 1 2 1 2 2 0 2]
 [0 2 2 0 0 2 1 0 1 1]
 [1 0 1 0 1 2 2 0 2 2]
 [1 0 1 1 1 1 1 1 1 0]
 [2 1 1 1 1 1 1 2 2 1]
 [2 0 1 0 0 1 2 0 1 0]
 [0 0 0 2 0 0 0 2 0 0]]

>>> Column 2
[2 0 1 1 2 1 1 1 1 0]

>>> Rows where column 2 == 1 
[[0 0 1 1 0 0 0 2 2 2]
 [1 2 1 1 2 1 2 2 0 2]
 [1 0 1 0 1 2 2 0 2 2]
 [1 0 1 1 1 1 1 1 1 0]
 [2 1 1 1 1 1 1 2 2 1]
 [2 0 1 0 0 1 2 0 1 0]]

Upvotes: 1

Related Questions