有效地将不均匀的列表列表转换为用 nan 填充的最小包含数组

2025-03-05 09:16:00
admin
原创
59
摘要:问题描述:考虑列表列表ll = [[1, 2, 3], [1, 2]] 如果我将其转换为,我将获得一个位于第一个位置和第二个位置的np.array一维对象数组。[1, 2, 3]`[1, 2]`print(np.array(l)) [[1, 2, 3] [1, 2]] 我想要这个print(np.array...

问题描述:

考虑列表列表l

l = [[1, 2, 3], [1, 2]]

如果我将其转换为,我将获得一个位于第一个位置和第二个位置的np.array一维对象数组。[1, 2, 3]`[1, 2]`

print(np.array(l))

[[1, 2, 3] [1, 2]]

我想要这个

print(np.array([[1, 2, 3], [1, 2, np.nan]]))

[[  1.   2.   3.]
 [  1.   2.  nan]]

我可以用循环来实现这一点,但我们都知道循环有多不受欢迎

def box_pir(l):
    lengths = [i for i in map(len, l)]
    shape = (len(l), max(lengths))
    a = np.full(shape, np.nan)
    for i, r in enumerate(l):
        a[i, :lengths[i]] = r
    return a

print(box_pir(l))

[[  1.   2.   3.]
 [  1.   2.  nan]]

我如何以快速、矢量化的方式做到这一点?


定时

在此处输入图片描述

在此处输入图片描述

设置功能

%%cython
import numpy as np

def box_pir_cython(l):
    lengths = [len(item) for item in l]
    shape = (len(l), max(lengths))
    a = np.full(shape, np.nan)
    for i, r in enumerate(l):
        a[i, :lengths[i]] = r
    return a

def box_divikar(v):
    lens = np.array([len(item) for item in v])
    mask = lens[:,None] > np.arange(lens.max())
    out = np.full(mask.shape, np.nan)
    out[mask] = np.concatenate(v)
    return out

def box_hpaulj(LoL):
    return np.array(list(zip_longest(*LoL, fillvalue=np.nan))).T

def box_simon(LoL):
    max_len = len(max(LoL, key=len))
    return np.array([x + [np.nan]*(max_len-len(x)) for x in LoL])

def box_dawg(LoL):
    cols=len(max(LoL, key=len))
    rows=len(LoL)
    AoA=np.empty((rows,cols, ))
    AoA.fill(np.nan)
    for idx in range(rows):
        AoA[idx,0:len(LoL[idx])]=LoL[idx]
    return AoA

def box_pir(l):
    lengths = [len(item) for item in l]
    shape = (len(l), max(lengths))
    a = np.full(shape, np.nan)
    for i, r in enumerate(l):
        a[i, :lengths[i]] = r
    return a

def box_pandas(l):
    return pd.DataFrame(l).values

解决方案 1:

这似乎与 非常接近this question,其中填充是用zeros而不是NaNs。那里发布了有趣的方法,以及mine基于broadcasting和 的 boolean-indexing方法。因此,我只需修改那里的帖子中的一行即可解决此案例,如下所示 -

def boolean_indexing(v, fillval=np.nan):
    lens = np.array([len(item) for item in v])
    mask = lens[:,None] > np.arange(lens.max())
    out = np.full(mask.shape,fillval)
    out[mask] = np.concatenate(v)
    return out

样本运行 -

In [32]: l
Out[32]: [[1, 2, 3], [1, 2], [3, 8, 9, 7, 3]]

In [33]: boolean_indexing(l)
Out[33]: 
array([[  1.,   2.,   3.,  nan,  nan],
       [  1.,   2.,  nan,  nan,  nan],
       [  3.,   8.,   9.,   7.,   3.]])

In [34]: boolean_indexing(l,-1)
Out[34]: 
array([[ 1,  2,  3, -1, -1],
       [ 1,  2, -1, -1, -1],
       [ 3,  8,  9,  7,  3]])

我已经在那里发布了该问答中发布的所有方法的一些运行时结果,这可能会有用。

解决方案 2:

可能最快的列表版本使用itertools.zip_longest(可能izip_longest在 Py2 中):

In [747]: np.array(list(itertools.zip_longest(*ll,fillvalue=np.nan))).T
Out[747]: 
array([[  1.,   2.,   3.],
       [  1.,   2.,  nan]])

平原zip出产:

In [748]: list(itertools.zip_longest(*ll))
Out[748]: [(1, 1), (2, 2), (3, None)]

另一个 zip '转置':

In [751]: list(zip(*itertools.zip_longest(*ll)))
Out[751]: [(1, 2, 3), (1, 2, None)]

通常,当从列表(甚至是列表的对象数组)开始时,坚持使用列表方法会更快。创建数组或数据框会产生大量开销。

这不是第一次有人问这个问题。

如何使用 numpy 填充和/或截断向量到指定的长度?

我的回答包括这个zip_longest和你的box_pir

我认为还有一个使用扁平数组的快速 Numpy 版本,但我不记得细节了。它可能是由 Warren 或 Divakar 提供的。

我认为“扁平化”版本的作用大致如下:

In [809]: ll
Out[809]: [[1, 2, 3], [1, 2]]
In [810]: sll=np.hstack(ll)     # all values in a 1d array
In [816]: res=np.empty((2,3)); res.fill(np.nan)  # empty target

获取值所在的扁平索引。这是关键步骤。这里使用r_迭代;快速版本可能使用cumsum

In [817]: idx=np.r_[0:3, 3:3+2]
In [818]: idx
Out[818]: array([0, 1, 2, 3, 4])
In [819]: res.flat[idx]=sll
In [820]: res
Out[820]: 
array([[  1.,   2.,   3.],
       [  1.,   2.,  nan]])

================

所以缺失的环节是>np.arange()广播

In [897]: lens=np.array([len(i) for i in ll])
In [898]: mask=lens[:,None]>np.arange(lens.max())
In [899]: mask
Out[899]: 
array([[ True,  True,  True],
       [ True,  True, False]], dtype=bool)
In [900]: idx=np.where(mask.ravel())
In [901]: idx
Out[901]: (array([0, 1, 2, 3, 4], dtype=int32),)

解决方案 3:

我可能会将其写为对每个已填充默认值的子数组进行切片分配的形式:

def to_numpy(LoL, default=np.nan):
    cols=len(max(LoL, key=len))
    rows=len(LoL)
    AoA=np.empty((rows,cols, ))
    AoA.fill(default)
    for idx in range(rows):
        AoA[idx,0:len(LoL[idx])]=LoL[idx]
    return AoA

我添加了 Divakar 的布尔索引,f4并加入了时间测试。至少在我的测试中(Python 2.7 和 Python 3.5;Numpy 1.11),它不是最快的。

时间表明,对于大多数列表来说izip_longest,或f2稍微快一些,但对于较大的列表,切片分配(即f1)更快:

from __future__ import print_function
import numpy as np
try:
    from itertools import izip_longest as zip_longest 
except ImportError:
    from itertools import zip_longest   

def f1(LoL):
    cols=len(max(LoL, key=len))
    rows=len(LoL)
    AoA=np.empty((rows,cols, ))
    AoA.fill(np.nan)
    for idx in range(rows):
        AoA[idx,0:len(LoL[idx])]=LoL[idx]
    return AoA

def f2(LoL):
    return np.array(list(zip_longest(*LoL,fillvalue=np.nan))).T

def f3(LoL):
    max_len = len(max(LoL, key=len))
    return np.array([x + [np.nan]*(max_len-len(x)) for x in LoL])

def f4(LoL):
    lens = np.array([len(item) for item in LoL])
    mask = lens[:,None] > np.arange(lens.max())
    out = np.full(mask.shape,np.nan)
    out[mask] = np.concatenate(LoL)
    return out  

if __name__=='__main__':
    import timeit   
    for case, LoL in (('small', [list(range(20)), list(range(30))] * 1000),
                      ('medium', [list(range(20)), list(range(30))] * 10000),
                      ('big', [list(range(20)), list(range(30))] * 100000),
                      ('huge', [list(range(20)), list(range(30))] * 1000000)):
        print(case)
        for f in (f1, f2, f3, f4):
            print("   ",f.__name__, timeit.timeit("f(LoL)", setup="from __main__ import f, LoL", number=100) )      

印刷:

small
    f1 0.245459079742
    f2 0.209980010986
    f3 0.350691080093
    f4 0.332141160965
medium
    f1 2.45869493484
    f2 2.32307982445
    f3 3.65722203255
    f4 3.55545687675
big
    f1 25.8796288967
    f2 26.6177148819
    f3 41.6916451454
    f4 41.3140149117
huge
    f1 262.429639101
    f2 295.129109859
    f3 427.606887817
    f4 441.810388088

解决方案 4:

也许是这样的?不知道你的硬件,但这意味着在 16ms 内,l2 = [list(range(20)), list(range(30))] * 10000 进行 100 次循环。

from numpy import nan


def box(l):
    max_lenght = len(max(l, key=len))
    return [x + [nan]*(max_lenght-len(x)) for x in l]

解决方案 5:

如果这仅适用于二维列表,那么这可能是您的答案:

from numpy import nan

def even(data):
    maxlen = max(len(l) for l in data)
    for l in data:
        l.extend([nan] * (maxlen - len(l)))

如果您不想修改实际列表:

from numpy import nan

def even(data):
    res = data.copy()
    maxlen = max(len(l) for l in res)
    for l in res:
        l.extend([nan] * (maxlen - len(l)))
    return res
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   3983  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   2747  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Freshdesk、ClickUp、nTask、Hubstaff、Plutio、Productive、Targa、Bonsai、Wrike。在当今快速变化的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多企业在项目管理过程中面临着诸多痛点,如任务分配不...
项目管理系统   82  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Monday、TeamGantt、Filestage、Chanty、Visor、Smartsheet、Productive、Quire、Planview。在当今快速变化的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多项目经理和团队在管理复杂项目时,常...
开源项目管理工具   90  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Smartsheet、GanttPRO、Backlog、Visor、ResourceGuru、Productive、Xebrio、Hive、Quire。在当今快节奏的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多企业在选择项目管理工具时常常面临困惑:...
项目管理系统   79  
热门文章
项目管理软件有哪些?
曾咪二维码

扫码咨询,免费领取项目管理大礼包!

云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用