I have the following array:
[[ 6. 105. 2. 8.09841881]
[ 6. 105. 4. 9.34220351]
[ 6. 105. 6. 9.97663435]
[ 6. 1001. 2. 9.57108242]
[ 6. 1001. 4. 12.22355794]
[ 6. 1001. 6. 13.57295942]
[ 12. 1001. 2. 12.37474466]
[ 12. 1001. 4. 17.45334004]
[ 12. 1001. 6. 19.88499289]
[ 18. 1007. 2. 16.09076561]
[ 18. 1007. 4. 23.43742275]
[ 18. 1007. 6. 27.73041646]]
And I have tried to extract only the rows with the first element being a six via
print ma.MaskedArray(a, mask=(np.ones_like(a)*(a[:,0]==6.0)).T)
which I got from the question " mask a 2D numpy array based on values in one column ". However, I get
File "./Prova.py", line 170, in <module>
print ma.MaskedArray(a, mask=(np.ones_like(a)*(a[:,0]==6.0)).T)
ValueError: operands could not be broadcast together with shapes (12,4) (12)
do you have a clue of why this doesn't work?
The question might be stupid, but please bear with me since I just started programming python. :-)
Setting up some test data to work on:
>>> a = np.arange(12*4).reshape((12,4))
First, we "allocate" space for our mask array:
>>> mask = np.empty(a.shape,dtype=bool)
Now we can't assign into it from the first column of a == 6
directly because they're not the proper shape:
>>> mask[:,:] = a[:,0] == 6
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (12,4) (12)
But we can broadcast our first column of a
up to the correct shape by simply inserting a newaxis so that it becomes a 2-D array:
>>> mask[:,:] = (a[:,0] == 6)[:,np.newaxis]
As we can see, our mask is now correct.
>>> mask
array([[ True, True, True, True],
[ True, True, True, True],
[ True, True, True, True],
[ True, True, True, True],
[ True, True, True, True],
[False, False, False, False],
[False, False, False, False],
[False, False, False, False],
[False, False, False, False],
[False, False, False, False],
[False, False, False, False],
[False, False, False, False]], dtype=bool)
Now we just make our masked array and sit back and enjoy :).
>>> ma.MaskedArray(a,mask=mask)
masked_array(data =
[[-- -- -- --]
[-- -- -- --]
[-- -- -- --]
[-- -- -- --]
[-- -- -- --]
[20 21 22 23]
[24 25 26 27]
[28 29 30 31]
[32 33 34 35]
[36 37 38 39]
[40 41 42 43]
[44 45 46 47]],
mask =
[[ True True True True]
[ True True True True]
[ True True True True]
[ True True True True]
[ True True True True]
[False False False False]
[False False False False]
[False False False False]
[False False False False]
[False False False False]
[False False False False]
[False False False False]],
fill_value = 999999)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.