Skip to main content
 首页 » 编程设计

python之多个嵌套列表与 pandas 的排列

2024年09月07日7kerrycode

我在 python 中遇到了第一个严肃的问题。

我有一些嵌套列表需要转换为 pandas DataFrame。看起来很容易,但对我来说具有挑战性的是: - 列表很大(所以代码需要很快) - 它们是嵌套的 - 当它们嵌套时,我需要组合。

所以有了这个输入:

la =  ['a', 'b', 'c', 'd', 'e'] 
lb = [[1], [2], [3, 33], [11,12,13], [4]] 
lc = [[1], [2, 22], [3], [11,12,13], [4]] 

我需要下面的输出

la      lb      lc 
a       1       1 
b       2       2 
b       2       22 
c       3       3 
c       33      3 
d       11      11 
d       11      12 
d       11      13 
d       12      11 
d       12      12 
d       12      13 
d       13      11 
d       13      12 
d       13      13 
e       4       4 

请注意,只要我有一个嵌套列表,我就需要所有排列。 起初我只是简单地尝试:

import pandas as pd 
pd.DataFrame({'la' : [x for x in la], 
              'lb' : [x for x in lb], 
              'lc' : [x for x in lc]}) 

但是寻找需要扩展并实际扩展(一个巨大的)DataFrame 的行似乎比修改我创建 DataFrame 的方式更难。

我查看了一些关于 itertools ( Flattening a shallow list in Python )、文档 ( https://docs.python.org/3.6/library/itertools.html ) 和生成器 ( What does the "yield" keyword do? ) 的精彩帖子,并提出了如下内容:

import itertools 
 
def f(la, lb, lc): 
    tmp = len(la) == len(lb) == len(lc) 
    if tmp: 
        for item in range(len(la)): 
            len_b = len(lb[item]) 
            len_c = len(lc[item]) 
            if ((len_b>1) or (len_c>1)): 
                yield list(itertools.product(la[item], lb[item], lc[item])) 
                ## above: list is not the result I need, 
                ##        without it it breaks (not an iterable) 
            else: 
                yield (la[item], lb[item], lc[item]) 
    else: 
        print('error: unequal length') 

我测试

my_gen =f(lit1, lit2, lit3) 
pd.DataFrame.from_records(my_gen) 

这...嗯...当我 yield itertools(它没有长度)时中断,并在我转换 itertools 后创建错误的数据结构 到一个可迭代对象。

我的问题如下:

  • 如何使用 yielding itertools 解决这个问题?
  • 这样有效率吗?在实际应用中,我将通过解析文件来创建列表,它们将是巨大的……任何性能提示或来自更高级同事的更好解决方案?是的,它不会中断/行为不端,所以我什至无法进行基准测试......
  • 逐个元素生成列表然后使用我的 f 函数是否有意义?

提前致谢!

请您参考如下方法:

我有一个解决方案:

import pandas as pd 
from itertools import product 
 
la =  ['a', 'b', 'c', 'd', 'e'] 
lb = [[1], [2], [3, 33], [11,12,13], [4]] 
lc = [[1], [2, 22], [3], [11,12,13], [4]] 
 
list_product = reduce(lambda x, y: x + y, [list(product(*_)) for _ in zip(la,lb,lc)]) 
df = pd.DataFrame(list_product, columns=["la", "lb", "lc"]) 
print(df) 

结果:

    la  lb  lc 
0   a   1   1 
1   b   2   2 
2   b   2   22 
3   c   3   3 
4   c   33  3 
5   d   11  11 
6   d   11  12 
7   d   11  13 
8   d   12  11 
9   d   12  12 
10  d   12  13 
11  d   13  11 
12  d   13  12 
13  d   13  13 
14  e   4   4