跟进:numpy多个切片布尔值

时间:2012-11-28 19:36:48

标签: python numpy

这是my other question

的后续行动
import numpy as np
foo = np.ones(10,10,2)

foo[np.ix_(row_boolean,col_boolean,[1])] += bar[np.ix_(col_boolean)]

bar是一维数组,row_boolean和col_boolean是一维布尔数组。我想将1D条形数组中的某些数字应用于foo中的相应列,对于row_ = int中的所有row == True。

当我尝试执行上述操作时(boolean_arr全部为False),我收到以下错误:

  

*** ValueError:形状为(0,0,1)的不可广播输出操作数与广播形状(0,0,0)不匹配

如何解决上述问题?好像是

foo[np.ix_(row_boolean,col_boolean,[1])].shape == (0,0,1)
bar[np.ix_(boolean_arr)].shape == (0,)

谢谢!

编辑: 这个效果的东西,只有我有一个额外的第三维

In [46]: foo = np.random.random([5,5])

In [47]: foo
Out[47]: 
array([[ 0.02736112,  0.71269725,  0.73994453,  0.21814789,  0.19557647],
       [ 0.82418806,  0.94340516,  0.51143188,  0.51030109,  0.30127457],
       [ 0.6996424 ,  0.44577645,  0.24166962,  0.49316502,  0.3283645 ],
       [ 0.94403   ,  0.64943989,  0.51634012,  0.78914121,  0.73034792],
       [ 0.16748087,  0.64182321,  0.50958472,  0.67246253,  0.17233392]])

In [48]: bar = np.array([1,2,3,4,5])

In [49]: col_filter = bar > 2

In [50]: col_filter
Out[50]: array([False, False,  True,  True,  True], dtype=bool)

In [51]: row_filter = foo[:,1] > .5

In [52]: row_filter
Out[52]: array([ True,  True, False,  True,  True], dtype=bool)

In [53]: foo[np.ix_(row_filter,col_filter)]
Out[53]: 
array([[ 0.73994453,  0.21814789,  0.19557647],
       [ 0.51143188,  0.51030109,  0.30127457],
       [ 0.51634012,  0.78914121,  0.73034792],
       [ 0.50958472,  0.67246253,  0.17233392]])

In [54]: foo[np.ix_(row_filter,col_filter)] += bar[np.ix_(col_filter)]

In [55]: foo
Out[55]: 
array([[ 0.02736112,  0.71269725,  3.73994453,  4.21814789,  5.19557647],
       [ 0.82418806,  0.94340516,  3.51143188,  4.51030109,  5.30127457],
       [ 0.6996424 ,  0.44577645,  0.24166962,  0.49316502,  0.3283645 ],
       [ 0.94403   ,  0.64943989,  3.51634012,  4.78914121,  5.73034792],
       [ 0.16748087,  0.64182321,  3.50958472,  4.67246253,  5.17233392]])

1 个答案:

答案 0 :(得分:1)

我没有时间解释原因,但你想要

foo[np.ix_(row_boolean, col_boolean) + (1,)] += bar[col_boolean]

您可以阅读超过您可能想了解的advanced indexing here.