考虑数组:
a = np.array([[nan, 0., 0.],
[nan, 1., 1.],
[nan, 2., nan]])
b = np.array([2., 0., 0.])
我正在努力实现以下目标:
x
,这是a
中不缺少的元素b
替换x
中的相应项目在这种情况下是:
For row = 2, col = 1
a[row, col] -> 2. # 1st col
Replace 1st element in `b` with 2.:
[2., 2., 0.]
Full matrix:
[[nan, sum([2,0,0]), sum([2,0,0])],
[nan, sum([2,1,0]), sum([2,0,1])],
[nan, sum([2,2,0]), nan]]
result = [[nan, 2, 2],
[nan, 3, 3],
[nan, 4, nan]]
如何实现result
?
答案 0 :(得分:2)
我想答案很简单:
a - b + b.sum()
#array([[nan, 2., 2.],
# [nan, 3., 3.],
# [nan, 4., nan]])
答案 1 :(得分:0)
也许:
c=np.array([[sum(b.tolist())+y for i in range(len(x))] for y,x in enumerate(a.tolist())])
c[np.isnan(a)]=np.nan
print(c)
输出:
[[ nan 2. 2.]
[ nan 3. 3.]
[ nan 4. nan]]