cheznead
cheznead

Reputation: 2789

Numpy subsetting and assignment

Let's say you want to subset a NumPy array fridge_items for rows of tasty things that have a rating of higher than 7.

most_tasty_items = fridge_items[:,10] > 7)

You get back an array of boolean values.

If you then did:

fridge_items[most_tasty_items,:][:3,:]

What is going on here exactly when you index into fridge_items. I'm familiar with doing array[1,2] and this returning what is at that given row and column.

Since most_tasty_items is a 1D array of boolean values, how do we index into that using the [:3,:]? If it were just a 1D array we could just say [:]. Not quite getting this, and why we give : as second parameter to [most_tasty_items,:]

Upvotes: 0

Views: 37

Answers (1)

gboffi
gboffi

Reputation: 25023

When you address the data with two couples of brackets, you are performing two operations, the first brackets select a new array from the data and the second brackets addresses the new array.

In [71]: np.random.seed(2020) 
    ...: fridge = np.random.randint(11, size=(30, 5)) 
    ...: tasty = fridge_items[:,4] > 7 
    ...: tastyfridge = fridge[tasty,:]                                                    

In [72]: tastyfridge[:2,:], fridge[tasty][:2,:]                                           
Out[72]: 
(array([[ 8, 10,  9,  3,  7],
        [ 4,  7,  1,  4,  9]]),
 array([[ 8, 10,  9,  3,  7],
        [ 4,  7,  1,  4,  9]]))

In [73]:                                                                                  

Upvotes: 1

Related Questions