欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

Numpy.array矩阵百分制化(比例化)

发布时间:2025/4/16 70 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Numpy.array矩阵百分制化(比例化) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

简述

用途不用说,很常用

  • 对于DataFrame的情况,但是操作却截然不同。注意对比。
  • Pandas.DataFrame按行求百分数(比例数)

问题

  • 假设有数据A
>>> A array([[ 0, 1, 2, 3, 4],[ 5, 6, 7, 8, 9],[10, 11, 12, 13, 14],[15, 16, 17, 18, 19]])

变成比例数如何操作?直接除以行求和?

>>> A / A.sum(axis=1) Traceback (most recent call last):File "<stdin>", line 1, in <module> ValueError: operands could not be broadcast together with shapes (4,5) (4,)

解决办法

  • numpy一般来说,只做对应位的操作,或者是数值(其实理解为长度为一的向量会更加准确)和向量的操作。
  • 因此需要用np.newaxis操作来将numpy.array变成一样的shape
>>> A / A.sum(axis=1)[:, np.newaxis] array([[0. , 0.1 , 0.2 , 0.3 , 0.4 ],[0.14285714, 0.17142857, 0.2 , 0.22857143, 0.25714286],[0.16666667, 0.18333333, 0.2 , 0.21666667, 0.23333333],[0.17647059, 0.18823529, 0.2 , 0.21176471, 0.22352941]])
  • A.sum(axis=1)[:, np.newaxis] 是什么?就是复制了很多遍的向量而已
>>> A.sum(axis=1) array([10, 35, 60, 85]) >>> A.sum(axis=1)[:, np.newaxis] array([[10],[35],[60],[85]])

总结

以上是生活随笔为你收集整理的Numpy.array矩阵百分制化(比例化)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。