【问题标题】:How to find index position in subarray when a value is less than zero?当值小于零时,如何在子数组中查找索引位置?
【发布时间】:2020-11-27 20:31:05
【问题描述】:

对 python 非常陌生,因此为代码的不雅致歉

我有一个带有两个子数组的 numpy 数组:

import numpy as np
p = 0.50
gen_seq = np.random.binomial(1, p, 20).reshape(2, 10)
t_form = np.where(gen_seq == 1, 0.5, -100)
initial_w = np.insert(t_form, 0, 100, axis=1)
d_account = np.cumsum(initial_w, axis=1)

我正在尝试为每个子数组查找低于零的第一个值的索引位置。有什么想法吗?

【问题讨论】:

  • 显示每个数组并评论是否符合预期。

标签: python python-3.x numpy multidimensional-array scipy


【解决方案1】:

如果您要获取每个子数组中第一个值的索引,该值小于零;就像下面这样简单,其中a 是有问题的数组。

例子:

# Sub-array 0
(a[0,:] < 0).argmax()
# Sub-array 1
(a[1,:] < 0).argmax()

或者,如果您更喜欢简单的循环:

for i in range(a.shape[0]):
    print((a[i,:] < 0).argmax())

输出:

>>> 6
>>> 3

注意:鉴于原始问题中的代码使用np.random,因此本示例中使用了np.random.seed(73)

【讨论】:

  • 我的快乐伙伴,乐于助人。您介意单击答案旁边的勾号以显示它已被接受吗?这是一个标准的 SO 实践。干杯伙伴。
猜你喜欢
  • 2020-02-21
  • 2021-04-04
  • 1970-01-01
  • 1970-01-01
  • 2011-06-03
  • 1970-01-01
  • 2017-12-23
  • 2019-11-30
相关资源
最近更新 更多