简体   繁体   中英

Python check when each column reaches a number and save that column number

I have an array filled with arrays using numpy split like the following

[array([3, 0, 0]),
array([1, 1, 1]),
array([2 , 2, 4]),
array([0, 1, 2]),
array([0, 1, 2]),
array([0, 2, 2])]

I want to check when each column reaches the number 3 or higher and then save that column number as another array or list. I also want it to write out the last column number if it never exceeded 3. So the answer to this example should be

[1, 6, 3]

Which means first column reached the number 3 on row 1, column 2 never reached the number 3 and column 3 reached the number 3 on row 3.

I have tried several things but none of them has worked.

You can use argmax from numpy to achieve this:

import numpy as np

split_data = [
    np.array([3, 0, 0]),
    np.array([1, 1, 1]),
    np.array([2, 2, 4]),
    np.array([0, 1, 2]),
    np.array([0, 1, 2]),
    np.array([0, 2, 2]),
]
print(f"split_data[0].shape {split_data[0].shape}")
print(f"split_data\n{split_data}")

# convert the list of arrays to a single matrix
data = np.stack(split_data)
print(f"data.shape {data.shape}")
print(f"data\n{data}")

# create a boolean array where the data is over 3
over3 = data >= 3
print(f"over3\n{over3}")

# this finds out the row where 3 was reached
index = np.argmax(over3, axis=0)
print(f"index {index}")

# you start counting from one, so increase that
index = index + 1
print(f"index increased {index}")

# this finds out if a column never reached 3
never = np.sum(over3, axis=0)
print(f"never {never}")

# if the sum is 0, then it never went over
# use that to update the index found
index[never == 0] = data.shape[0]
print(f"index {index}")

Which will produce

split_data[0].shape (3,)
split_data
[array([3, 0, 0]), array([1, 1, 1]), array([2, 2, 4]), array([0, 1, 2]), array([0, 1, 2]), array([0, 2, 2])]
data.shape (6, 3)
data
[[3 0 0]
 [1 1 1]
 [2 2 4]
 [0 1 2]
 [0 1 2]
 [0 2 2]]
over3
[[ True False False]
 [False False False]
 [False False  True]
 [False False False]
 [False False False]
 [False False False]]
index [0 0 2]
index increased [1 1 3]
never [1 0 1]
index [1 6 3]

Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM