Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy multiple slicing booleans

Tags:

python

numpy

I'm having trouble editing values in a numpy array

import numpy as np
foo = np.ones(10,10,2)

foo[row_criteria, col_criteria, 0] += 5
foo[row_criteria,:,0][:,col_criteria] += 5

row_criteria and col_criteria are boolean arrays (1D). In the first case I get a

"shape mismatch: objects cannot be broadcast to a single shape" error

In the second case, += 5 doesn't get applied at all. When I do

foo[row_criteria,:,0][:,col_criteria] + 5

I get a modified return value but modifying the value in place doesn't seem to work...

Can someone explain how to fix this? Thanks!

like image 246
ejang Avatar asked Apr 21 '26 22:04

ejang


1 Answers

You want:

foo[np.ix_(row_criteria, col_criteria, [0])] += 5

To understand how this works take this example:

import numpy as np
A = np.arange(25).reshape([5, 5])
print A[[0, 2, 4], [0, 2, 4]]
# [0, 12, 24]

# The above example gives the the elements A[0, 0], A[2, 2], A[4, 4]
# But what if I want the "outer product?" ie for [[0, 2, 4], [1, 3]] i want
# A[0, 1], A[0, 3], A[2, 1], A[2, 3], A[4, 1], A[4, 3]
print A[np.ix_([0, 2, 4], [1, 3])]
# [[ 1  3]
#  [11 13]
#  [21 23]]

The same thing works with boolean indexing. Also np.ix_ doesn't do anything really amazing, it just reshapes it's arguments so they can be broadcast against each other:

i, j = np.ix_([0, 2, 4], [1, 3])
print i.shape
# (3, 1)
print j.shape
# (1, 2)
like image 74
Bi Rico Avatar answered Apr 24 '26 12:04

Bi Rico