【问题标题】:Iterating through the rows of a multidimensional array within a function Python在函数 Python 中遍历多维数组的行
【发布时间】:2021-11-29 10:54:33
【问题描述】:

有没有办法我可以在下面的result 代码中运行multi,以便它在下面列出a,b,c 的迭代时给出预期的输出。我试图做到这一点,以便[:,] 可用于遍历二维数组中的行,但它不起作用。我如何在没有 for 循环的情况下迭代所有行以获得下面的预期输出。 for 循环和 numpy 代码的意思是一样的。

Numpy 代码:

import numpy as np
a = np.array([1,2,3,11,23])
b = np.array([-2, 65, 8, 0.98])
c = np.array([5, -6])
multi = np.array([a, b, c])
result = (multi[:,] > 0).cumsum() / np.arange(1, len(multi[:,])+1) * 100

For循环代码:

import numpy as np
a = np.array([1,2,3,11,23])
b = np.array([-2, 65, 8, 0.98])
c = np.array([5, -6])
multi = np.array([a, b, c])
for i in range(len(multi)):
    predictability = (multi[i] > 0).cumsum() / np.arange(1, len(multi[i])+1) * 100
    print(predictability)

结果:

[[100. 100. 100. 100. 100.],
[ 0.         50.         66.66666667 75.        ],
[100.  50.]]

【问题讨论】:

  • 所以你希望每一行都有不同大小的数组,所以我怀疑是否有矢量化的方式来做到这一点。
  • 使用multi = [a, b, c]。参差不齐的数组对你一点帮助都没有。
  • multi[:,] 没有做任何有用的事情。查看multi.shapedtype 甚至打印数组。

标签: python arrays numpy multidimensional-array iterator


【解决方案1】:

从创建数组时完全显示

In [150]: np.array([1,100,200],str)
Out[150]: array(['1', '100', '200'], dtype='<U3')
In [151]: np.array([1,100,200.],str)
Out[151]: array(['1', '100', '200.0'], dtype='<U5')
In [152]: a = np.array([1,2,3,11,23])
     ...: b = np.array([-2, 65, 8, 0.98])
     ...: c = np.array([5, -6])
     ...: multi = np.array([a, b, c])
<ipython-input-152-d6f4f1c3f527>:4: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
  multi = np.array([a, b, c])
In [153]: multi
Out[153]: 
array([array([ 1,  2,  3, 11, 23]), array([-2.  , 65.  ,  8.  ,  0.98]),
       array([ 5, -6])], dtype=object)

这是一维数组,不是二维。

创建一个数组,而不仅仅是列表,[a,b,c] 没有任何用处。

只需将您的计算应用于每个数组:

In [154]: [(row > 0).cumsum() / np.arange(1, len(row)+1) * 100 for row in [a,b,c]]
Out[154]: 
[array([100., 100., 100., 100., 100.]),
 array([ 0.        , 50.        , 66.66666667, 75.        ]),
 array([100.,  50.])]

通常当您拥有长度不同的数组(或列表)时,您几乎无法像拥有二维数组一样执行这些操作。

【讨论】:

    猜你喜欢
    • 2010-11-01
    • 2012-04-16
    • 2015-09-26
    • 1970-01-01
    • 2013-04-01
    相关资源
    最近更新 更多