Skip to main content
 首页 » 编程设计

python之用最后一个元素填充列表的嵌套列表中的缺失值

2025年05月04日18pengyingh

我有一个 numpy 图像数组,但它不完整,它看起来像这样:

[ 
[255,255,255], 
[128], 
[34,4], 
[44] 
] 

我想添加特定元素的先前值以完成该元素,如下所示:

[ 
[255,255,255], 
[128,128,128], 
[34,4,4], 
[44,44,44] 
] 

那么,如何为特定元素添加值? 关键是,我需要每个元素 block 来完成它自己

请您参考如下方法:

方法 #1

这是一个基于 this post 的-

def fill_by_last_val(a): 
    lens = np.array([len(item) for item in a]) 
    ncols = lens.max() 
    last_ele = np.array([a_i[-1] for a_i in a]) 
    out = np.repeat(last_ele[:,None],ncols,axis=1) 
    mask = lens[:,None] > np.arange(lens.max()) 
    out[mask] = np.concatenate(a) 
    return out 

方法 #2

另一个基于itertools -

import itertools 
 
def fill_by_last_val_v2(a): 
    last_ele = np.array([a_i[-1] for a_i in a]) 
    a_f = np.array(list(itertools.zip_longest(*a,fillvalue=0))).T 
    m = np.minimum.accumulate((a_f==0)[:,::-1],axis=1)[:,::-1] 
    return m*last_ele[:,None]+a_f 

方法 #3

假设输入中没有 NaN 的 pandas 数据框 -

import pandas as pd 
 
def fill_by_last_val_v3(a): 
    df = pd.DataFrame(a) 
    m = df.isnull() 
    last_ele = np.array([a_i[-1] for a_i in a]) 
    return np.where(m,last_ele[:,None],df) 

方法 #4

再次使用 pandas 最简单 -

In [168]: a 
Out[168]: [[255, 255, 255, 5], [128, 5, 6], [34, 0, 7], [nan, 44]] 
 
In [169]: pd.DataFrame(a).ffill(axis=1).to_numpy() 
Out[169]:  
array([[255., 255., 255.,   5.], 
       [128.,   5.,   6.,   6.], 
       [ 34.,   0.,   7.,   7.], 
       [ nan,  44.,  44.,  44.]]) 

您可能希望进行 dtype 转换,但为 pandas 解决方案提供原始数据类型。