如何在Python中对相同长度的多个一维数组执行相同的Numpy函数序列?
例如:
import numpy as np
subtotal1 = np.array([4, 7, 1, 3, 9])
subtotal2 = np.array([5, 3, 6, 5, 2])
...etc.
total = np.array([9, 10, 7, 8, 11])
subtotal1 = np.divide(subtotal1, total)
subtotal1 = np.round(subtotal1 * 100, 1)
subtotal2 = np.divide(subtotal2, total)
subtotal2 = np.round(subtotal2 * 100, 1)
...etc.我是一个新的Python程序员,我正在学习Numpy来分析数据和创建可视化。我已经搜索了StackOverflow和Numpy文档好几天了,但一无所获。
非常感谢!
发布于 2016-12-02 04:32:51
这就是你想说的:
import numpy as np
subtotal1 = np.array([4, 7, 1, 3, 9],float)
subtotal2 = np.array([5, 3, 6, 5, 2],float)
total = subtotal1+subtotal2
for subtotal in (subtotal1, subtotal2):
subtotal = np.divide(subtotal, total)
subtotal = np.round(subtotal * 100, 1)
print subtotal重要信息如果你不把subtotal1和2设置为浮点数,除法会给你0(整数除法),这不是你想要的。
由于您没有说明如何创建这些小计,假设您可以将它们添加到一个列表中,因此代码很容易泛化:
//Create subtotals before
total = sum(subtotals)
for subtotal in subtotals
subtotal = np.divide(subtotal, total)
subtotal = np.round(subtotal * 100, 1)
print subtotal注您的问题实际上不是关于numpy或arrays的。还要注意,sum不是numpy和-这是不同的。在跳到前面之前,请阅读一些普通的Python教程。
发布于 2016-12-02 05:00:36
您可以将所有subtotal数组连接到一个2D数组中,然后在整个数组上执行这两个操作。这将导致两个数组之间的逐行操作。要做到这一点,两个数组的形状必须在第二个(列)轴上相等。
import numpy as np
subtotal = np.arange(20,dtype=float).reshape((5,4))
total = np.array([8.2,3.4,6.0,1.3])
print subtotal
[[ 0. 1. 2. 3.]
[ 4. 5. 6. 7.]
[ 8. 9. 10. 11.]
[ 12. 13. 14. 15.]
[ 16. 17. 18. 19.]]
np.round(subtotal/total*100,1)
array([[ 0. , 29.4, 33.3, 230.8],
[ 48.8, 147.1, 100. , 538.5],
[ 97.6, 264.7, 166.7, 846.2],
[ 146.3, 382.4, 233.3, 1153.8],
[ 195.1, 500. , 300. , 1461.5]])https://stackoverflow.com/questions/40916362
复制相似问题