繁体   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