簡體   English   中英

如何根據條件在 numpy 數組中插入行

[英]How to inserts rows in a numpy array based on the condition

我有兩個列表 numpy arrays 並想將列表的 arrays 插入另一個列表的 ZA3CBC3F9D0CE71F2C159CZEB1:

big_list=[np.array([[1., 1., 2.], [1., 1., 1.9], [1., 1., 5.2]]),
          np.array([[1., 3., 5.1], [0., 0., 1.2], [1., 1., 1.4]])]

small_list= [np.array([[-1., -1., -5.]]),
             np.array([[-1., -1., -1.], [0., -2., -0.5]])]

我想在 big_list 的第一個數組中插入small_list的第一個數組,在big_list的第二個數組中big_list small_list的第二個數組。 我想把big_list放在small_list的第三列有顯着變化的地方。 big_list的第一個數組中,從第二行到第三行,第三列變化很大(從1.95.2 )。 對於big_list的第二個數組,更改發生在第一行之后(從5.11.2 )。 例如,我想使用像3這樣的閾值來表示一行的第三列與下一行的差異。 所以,我想擁有:

merged= [np.array([[1., 1., 2.], [1., 1., 1.9], [-1., -1., -5.], [1., 1., 5.2]]),
         np.array([[1., 3., 5.1], [-1., -1., -1.], [0., -2., -0.5], [0., 0., 1.2], [1., 1., 1.4]])]

目前,我的代碼只能 append 行small_listbig_list的末尾:

merged = [np.append(array, to_append, axis=0) for (array, to_append) in zip(big_list, small_list)]

有沒有辦法在我想要的地方插入這些行? 在此之前,我非常感謝任何幫助。

嘗試這個-

for i, arr in enumerate(big_list):
    diff = list(abs(np.diff(arr[:,-1])) >= 3)
    for t, threshold_state in enumerate(diff):
        if threshold_state:
            big_list[i] = np.insert(big_list[i], t+1, small_list[i], axis=0)

Output

[array([[ 1. ,  1. ,  2. ],
        [ 1. ,  1. ,  1.9],
        [-1. , -1. , -5. ],
        [ 1. ,  1. ,  5.2]]), 
array([[ 1. ,  3. ,  5.1],
        [-1. , -1. , -1. ],
        [ 0. , -2. , -0.5],
        [ 0. ,  0. ,  1.2],
        [ 1. ,  1. ,  1.4]])]

嘗試這個 -

  • 循環遍歷 big_list 中的每個元素
  • idx 計算最后一列值之間的絕對差大於 3 的第一個索引
  • 在 idx 處插入數組中對應的小列表。
merged = []
for i in range(len(big_list)):
    idx = np.argwhere(np.abs(np.diff(big_list[i][:,2]))>3)[0]+1
    m = np.insert(big_list[i], idx, small_list[i], axis=0)
    merged.append(m)
    
merged

[array([[ 1. ,  1. ,  2. ],
        [ 1. ,  1. ,  1.9],
        [-1. , -1. , -5. ],
        [ 1. ,  1. ,  5.2]]),
 array([[ 1. ,  3. ,  5.1],
        [-1. , -1. , -1. ],
        [ 0. , -2. , -0.5],
        [ 0. ,  0. ,  1.2],
        [ 1. ,  1. ,  1.4]])]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM