BedfordDriggs
BedfordDriggs

Reputation: 27

How to find index position in subarray when a value is less than zero?

Very new to python so apologies for the inelegance of code

I have a numpy array with two subarrays:

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)

I am trying to find the index position of the first value that is below zero for each subarray. Any ideas?

Upvotes: 1

Views: 351

Answers (1)

s3dev
s3dev

Reputation: 9711

If you're looking to get the index of the first value in each sub-array, which is less than zero; it's as simple as the following, where a is the array in question.

Example:

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

Or, if you'd prefer a simple loop:

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

Output:

>>> 6
>>> 3

Note: Given the code in the original question uses np.random, np.random.seed(73) has been used in this example.

Upvotes: 1

Related Questions