簡體   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