Boolean Indexing with Numpy (Slide 8)

My Code

new_column = taxi_modified[:,15]

new_column[taxi_modified[:,5] == 2] = 1
new_column[taxi_modified[:,5] == 3] = 1
new_column[taxi_modified[:,5] == 5] = 1   

Answer Code

taxi_modified[taxi_modified[:, 5] == 2, 15] = 1
taxi_modified[taxi_modified[:, 5] == 3, 15] = 1
taxi_modified[taxi_modified[:, 5] == 5, 15] = 1

My answer is based on what I have learnt in the fundamentals and intermediate course, which first assigns the column and then use the ‘comparision function’ (Single Dimension)

My question is why is the ‘comparision function’ in the answer located in the ‘row indexing’??? It does not make logical sense as the comparsion should be done outside the indexing?
(Eg: taxi_modified[taxi_modified[: , 15] == 5] = 1)

Hi @genesix32
Both are the correct ways to do. But ‘Answer Code’ takes 3 lines of code and ‘My Code’ takes 4 lines to complete the same task. I think that’s why we prefer putting the ‘column for assignment’ inside the index.

So it is by default inside the row indexing???

Basically, this slide is to teach about how to do assignment using a boolean array with two dimensions arrays.

1 Like