繁体   English   中英

Python 检查每列何时达到一个数字并保存该列号

[英]Python check when each column reaches a number and save that column number

我有一个数组填充了 arrays 使用 numpy 拆分如下

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

我想检查每列何时达到数字 3 或更高,然后将该列号保存为另一个数组或列表。 如果它从未超过 3,我还希望它写出最后一列编号。所以这个例子的答案应该是

[1, 6, 3]

这意味着第一列达到了第 1 行的数字 3,第 2 列从未达到数字 3,第 3 列达到了第 3 行的数字 3。

我尝试了几件事,但都没有奏效。

您可以使用argmax中的numpy来实现此目的:

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}")

哪个会产生

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]

干杯!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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