按元素应用

时间:2018-08-26 03:05:00

标签: python numpy matrix

考虑数组:

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

2 个答案:

答案 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]]