I'm having an issue with modifying an array, by adding the percentage of each item compared to its row to a new matrix. This is the code providing error:
我在修改数组方面存在问题,方法是将每个项目与其行相比的百分比添加到新矩阵中。这是提供错误的代码:
for j in range(1,27):
for k in range(1,27):
let_prob[j,k] = let_mat[j,k]*100/(let_mat[j].sum())
I get the error:
我收到错误:
RuntimeWarning: invalid value encountered in long_scalars
RuntimeWarning:long_scalars中遇到无效值
I have tried rounding the denominator to no success.
我试图将分母四舍五入,但没有成功。
1 个解决方案
#1
0
It seems that you are dealing with big numbers, since it raised such RuntimeWarning
. For get ride of such errors, as a numpythonic way you can firs calculate the sum of each row using np.sum()
function by specifying the proper axis then repeat and reshape the array in order to be able to divide with your array, them multiple with 100 and round the result:
看来你正在处理大数字,因为它引发了这样的RuntimeWarning。为了获得这样的错误,你可以使用np.sum()函数通过指定正确的轴来重新计算每行的总和,然后重复和重新整形数组,以便能够与数组分开, 100的倍数和结果:
col, row = np.shape(let_mat)
let_prob = np.round((let_mat/np.repeat(let_mat.sum(axis=1),row).reshape(col, row).astype(float))*100,2)
Demo :
演示:
>>> a = np.arange(20).reshape(4,5)
>>>
>>> a
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
>>> np.round((a/np.repeat(a.sum(axis=1),5).reshape(4,5).astype(float))*100,2)
array([[ 0. , 10. , 20. , 30. , 40. ],
[ 14.29, 17.14, 20. , 22.86, 25.71],
[ 16.67, 18.33, 20. , 21.67, 23.33],
[ 17.65, 18.82, 20. , 21.18, 22.35]])
#1
0
It seems that you are dealing with big numbers, since it raised such RuntimeWarning
. For get ride of such errors, as a numpythonic way you can firs calculate the sum of each row using np.sum()
function by specifying the proper axis then repeat and reshape the array in order to be able to divide with your array, them multiple with 100 and round the result:
看来你正在处理大数字,因为它引发了这样的RuntimeWarning。为了获得这样的错误,你可以使用np.sum()函数通过指定正确的轴来重新计算每行的总和,然后重复和重新整形数组,以便能够与数组分开, 100的倍数和结果:
col, row = np.shape(let_mat)
let_prob = np.round((let_mat/np.repeat(let_mat.sum(axis=1),row).reshape(col, row).astype(float))*100,2)
Demo :
演示:
>>> a = np.arange(20).reshape(4,5)
>>>
>>> a
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
>>> np.round((a/np.repeat(a.sum(axis=1),5).reshape(4,5).astype(float))*100,2)
array([[ 0. , 10. , 20. , 30. , 40. ],
[ 14.29, 17.14, 20. , 22.86, 25.71],
[ 16.67, 18.33, 20. , 21.67, 23.33],
[ 17.65, 18.82, 20. , 21.18, 22.35]])