【问题标题】:Same Sequence of Numpy Functions on Multiple 1D Arrays多个一维数组上的相同 Numpy 函数序列
【发布时间】:2016-12-01 17:04:09
【问题描述】:

如何在 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 文档好几天都没有运气。

非常感谢!

【问题讨论】:

  • 用这些操作(ops)定义一个函数,然后在堆叠的二维数组上使用np.apply_along_axis?搜索该方法的用例可能会有所帮助。根据操作,您甚至可以沿该轴对它们进行矢量化,因为如果您关心性能,np.apply_along_axis 并不是真正的矢量化实现。

标签: python arrays function numpy


【解决方案1】:

这是你的意思吗:

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 设置为浮点数,则除法会给您零(整数除法),这不是您想要的。

由于您没有说明如何创建这些小计,假设您可以随时将它们附加到列表中,因此代码很容易概括:

//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 教程。

【讨论】:

    【解决方案2】:

    您可以将所有subtotal 数组连接到一个二维数组中,并对整个数组进行两次操作。这将导致两个数组之间的逐行操作。为此,两个数组的形状必须沿第二个(列)轴相等。

    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]])
    

    【讨论】:

      猜你喜欢
      • 2015-12-16
      • 1970-01-01
      • 2019-06-09
      • 1970-01-01
      • 2013-09-30
      • 2012-07-26
      • 2017-09-03
      • 2017-12-23
      相关资源
      最近更新 更多