1

I have an array in Python 3.9 with 3 columns, and I wanna print just the numbers of the third column that is smaller than 5. How I do that?

The array is called data.

array([[ 44410,   2003,     18],
       [  5712,   1991,     30],
       [ 37123,   1990,     31],
       [     0,   2019,      2],
       [ 25757,   2006,     15],
       [ 10728,   2012,      9],
       [     0,   2019,      2],
       [ 77599,   2009,     12],
       [ 99197,   2010,     11]])

I tried this, but doesn't worked:

data[:, data[2] < 5]

Because appear just this message: array([ ], shape=(258, 0), dtype=int32)

1
  • Python 3 I’m guessing... Commented Apr 8, 2021 at 19:33

3 Answers 3

3

You can use a simple list comprehension:

Get a list of all sub-lists with a number in the third index that is smaller than 5:

[row for row in arr if row[2] < 5]

Or if you want to get a list containing only the third number of each sub-list that is smaller than 5:

[row[2] for row in arr if row[2] < 5]
Sign up to request clarification or add additional context in comments.

Comments

0

Use list comprehension to filter the third values less than 5.

import numpy as np

data = np.array([[ 44410,   2003,     18],
       [  5712,   1991,     30],
       [ 37123,   1990,     31],
       [     0,   2019,      2],
       [ 25757,   2006,     15],
       [ 10728,   2012,      9],
       [     0,   2019,      2],
       [ 77599,   2009,     12],
       [ 99197,   2010,     11]])

third_colum_filtered = [i[2] for i in data if i[2]<5]

print(third_colum_filtered)

Output:

[2, 2]

Comments

0

First you need to create a filter array:

>>> data[:,2] < 5
array([False, False, False,  True, False, False,  True, False, False], dtype=bool)>>> 

And then apply it to yours:

>>> filter_array = data[:,2] < 5
>>> data[filter_array]
array([[   0, 2019,    2],
       [   0, 2019,    2]])

So, short circuiting:

data[data[:,2] < 5]

Is this what you are after? If you want only the values then add ", 2" and that would convert the last column to a vector with the values:

>>> data[data[:,2] < 5, 2]
array([2, 2])

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.