【问题标题】:How to loop inside a nd.array in Python如何在Python中循环内部and.array
【发布时间】:2016-10-27 12:37:00
【问题描述】:

我有一个 N 维数组 = X,我想检查 X 中的每个值是否大于 0.35 。我写成:-

for number in X:
    if (.35> number):  # Here error occurs
        print (enumerate(number))

但我收到此错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我想将 X 中小于 0.35 的每个值的索引保存在列表中

【问题讨论】:

标签: python python-3.x if-statement for-loop


【解决方案1】:

使用 NumPy 时,您必须始终努力在向量空间中进行操作。这意味着不写for循环,也不写in等。

对于您目前的情况,您可以这样做:

print(X[X < 0.35])

这将比编写循环快得多。如果您必须将它们打印在不同的行上,您可以:

values = X[X < 0.35]
np.savetxt(sys.stdout, values)

【讨论】:

  • 感谢回复,但是我想知道值小于0.35的索引号,并想生成所有这些索引的列表,怎么做? (如果你能告诉我)
  • 要生成索引列表,请使用np.nonzero(X &lt; 0.35)
  • @A.wadhawan,你要找的是 numpy.where docs.scipy.org/doc/numpy/reference/generated/numpy.where.html
猜你喜欢
  • 2012-12-07
  • 2017-08-29
  • 2010-12-31
  • 1970-01-01
  • 1970-01-01
  • 2014-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多