PeKo
PeKo

Reputation: 25

Comparing two elements by index in a numpy 2D array

I'm currently going through this course to learn numpy: https://saskeli.github.io/data-analysis-with-python-summer-2019/numpy2.html. I'm currently stuck in Exercise 1 (column comparison).

The exercise states: Write function column_comparison that gets a two dimensional array as parameter. The function should return a new array containing those rows from the input that have the value in the second column larger than in the second last column.

Here's the test array:

arr = np.array([[8 ,9 ,3 ,9 ,8],
                [0 ,5 ,3 ,9 ,9],
                [5 ,7 ,6 ,0 ,4],
                [7 ,8 ,1 ,6 ,2],
                [2 ,1 ,3 ,5 ,8],
                              ])

I tried these, which print the same output:

c = arr[1] > arr[-2]      arr[arr[1] > arr[-2]]

[[5 7 6 0 4]
 [7 8 1 6 2]
 [2 1 3 5 8]]

The result should be:

[[8 9 3 8 8]
[5 7 6 0 4]
[7 8 1 6 2]]

I actually can't even figure out what that does, the last row certainly doesn't satisfy the condition I wanted it to. I feel like I'm missing something very obvious, but I can't come up with a working solution.

Upvotes: 1

Views: 595

Answers (1)

Rahul Verma
Rahul Verma

Reputation: 3176

you are not selecting the column

import numpy as np
arr = np.array([[8 ,9 ,3 ,9 ,8],
                [0 ,5 ,3 ,9 ,9],
                [5 ,7 ,6 ,0 ,4],
                [7 ,8 ,1 ,6 ,2],
                [2 ,1 ,3 ,5 ,8],
                              ])
print(arr[arr[:,1]>=arr[:,-2]])

[[8 9 3 9 8]
 [5 7 6 0 4]
 [7 8 1 6 2]

Upvotes: 2

Related Questions