这是我的另一个问题的后续行动
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 是一维布尔数组。我想将一维条形数组中的某些数字应用于 foo 中的相应列,对于 row_boolean 中的所有行 == 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]])