我有2个矩阵,我想为它们添加标题。如何添加它们并使用它们的行和列的标题调用每个单元格?而且我还必须用列的元素计算每个行元素的总和。我做到了,但有没有更好的方法(一个循环)去做而不是我做的?它返回带有和的行和列的标题(例如:xy:0.022)
提示:行的标题必须与列的标题不同。 而且我不想使用熊猫。
这是我的代码:
import numpy as np
T = np.array([0,0.012,0.054,0,1,0.03,0.08,0.14,0.02]).reshape(3,3)
#print (T)
#print ('----------------------------')
W = np.array([1,0,0.03,0.01,0.099,0.020,2,0,0.05]).reshape(3,3)
#print (W)
x = T[0][0] + W[0][0]
y = T[0][1] + W[1][0]
z = T[0][2] + W[2][0]
v = T[1][0] + W[0][1]
n = T[1][1] + W[1][1]
m = T[1][2] + W[2][1]
s = T[2][0] + W[0][2]
g = T[2][1] + W[1][2]
k = T[2][2] + W[2][2]
print (x, y, z, v, n, m, s, g, k)
答案 0 :(得分:0)
这是一种方法:
>>> import itertools
>>> T = np.array([0,0.012,0.054,0,1,0.03,0.08,0.14,0.02]).reshape(3,3)
>>> T
array([[ 0. , 0.012, 0.054],
[ 0. , 1. , 0.03 ],
[ 0.08 , 0.14 , 0.02 ]])
>>> W = np.array([1,0,0.03,0.01,0.099,0.020,2,0,0.05]).reshape(3,3)
>>> W
array([[ 1. , 0. , 0.03 ],
[ 0.01 , 0.099, 0.02 ],
[ 2. , 0. , 0.05 ]])
>>> Y = T + W.T # The additions you do can be expressed like this.
>>> Y
array([[ 1. , 0.022, 2.054],
[ 0. , 1.099, 0.03 ],
[ 0.11 , 0.16 , 0.07 ]])
>>> labels = map(lambda x:"".join(x), itertools.product(["x","y","z"], ["a","b","c"]))
>>> labels
['xa', 'xb', 'xc', 'ya', 'yb', 'yc', 'za', 'zb', 'zc']
>>> labels = np.array(labels).reshape((3,3))
>>> labels
array([['xa', 'xb', 'xc'],
['ya', 'yb', 'yc'],
['za', 'zb', 'zc']],
dtype='|S2')
>>> for (x,y), value in np.ndenumerate(Y):
... print labels[x,y], Y[x,y]
...
xa 1.0
xb 0.022
xc 2.054
ya 0.0
yb 1.099
yc 0.03
za 0.11
zb 0.16
zc 0.07
我不确定您想要哪种格式的标题,但我认为这种方法很有意义。