【问题标题】:Python: create combinations of two columns containing lists as their value in a dataframePython:创建包含列表的两列的组合作为它们在数据框中的值
【发布时间】:2020-08-11 03:54:26
【问题描述】:

我有一个列中包含列表的数据框,我正在尝试找出最有效的方法来查找两个列表的组合 -

df = pd.DataFrame([[['a','b','c'],['l','m']],[['d','e','f'],['n','o']]],columns = ['col1','col2'])

现在这种情况下的输出将是 -

     col1   col2
0   [a, l]  [a, m]
1   [b, l]  [b, m]
2   [c, l]  [c, m]
3   [d, n]  [d, o]
4   [e, n]  [e, o]
5   [f, n]  [f, o]

我尝试遍历每一行,然后应用 itertools.combinations。但它使我的系统崩溃,因为数据框中的行数更多。你能建议我任何有效的方法来做到这一点吗?提前致谢。

【问题讨论】:

  • 多少行会崩溃?
  • 问题似乎更多在于您如何迭代?最好的方法是不对给定行保留任何修改数据的缓存。完成组合后,只需将该行刷新,然后移动以进行下一行处理。此外,如果数据帧的大小与您的系统所拥有的 RAM(分配给您的进程)相比太大,那么无论如何它都会因 OOO 而失败。处理该问题的方法是将文件分块并一次处理一个块并在最后连接。

标签: python pandas dataframe combinations


【解决方案1】:

您也可以将itertools.product 与numpy.reshape 一起使用:

from itertools import product

print (pd.DataFrame(np.reshape([list(product(a,b))
                                for a,b in df.to_numpy()],
                               (-1,2,2)).tolist()))

        0       1
0  [a, l]  [a, m]
1  [b, l]  [b, m]
2  [c, l]  [c, m]
3  [d, n]  [d, o]
4  [e, n]  [e, o]
5  [f, n]  [f, o]

【讨论】:

    【解决方案2】:

    您可以使用itertools 来获取您的输出:

    from itertools import product, chain, tee, islice
    
    col1, col2 = tee(chain.from_iterable(product(col1, col2) 
                                         for col1, col2 
                                         in df.to_numpy()), 
                     2)
    
    # Here we get alternate rows
    col1 = islice(col1, None, None, 2)
    
    col2 = islice(col2, 1, None, 2)
    
    pd.DataFrame(zip(col1, col2), columns=["col1", "col2"])
    
        col1    col2
    0   (a, l)  (a, m)
    1   (b, l)  (b, m)
    2   (c, l)  (c, m)
    3   (d, n)  (d, o)
    4   (e, n)  (e, o)
    5   (f, n)  (f, o)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-31
      • 1970-01-01
      • 2018-12-20
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 2020-06-27
      相关资源
      最近更新 更多