代码之家  ›  专栏  ›  技术社区  ›  Giora Simchoni

熊猫:将*多个*集合列转换为列表列

  •  2
  • Giora Simchoni  · 技术社区  · 7 年前

    带有集合列的简单数据框:

    df = pd.DataFrame({'a': [{0,1}, {1,2}, {}], 'b': [{1,2},{2,3,4}, {3}]})
    df
            a          b
    0  {0, 1}     {1, 2}
    1  {1, 2}  {2, 3, 4}
    2      {}        {3}
    

    我要将多个特定的集合列转换为列表列。我在用 apply 但这不起作用:

    df[['a','b']].apply(lambda x: list(x))
            a          b
    0  {0, 1}     {1, 2}
    1  {1, 2}  {2, 3, 4}
    2      {}        {3}
    

    它适用于单个列/系列,但是:

    df['a'].apply(lambda x: list(x))
    0    [0, 1]
    1    [1, 2]
    2        []
    Name: a, dtype: object
    

    在不涉及列表的不同数据框架上,一个不同的函数当然可以按预期在多个列上工作:

    df2 = pd.DataFrame({'a':[0,1,2], 'b':[3,4,5]})
    df2[['a','b']].apply(lambda x: x + 1)
       a  b
    0  1  4
    1  2  5
    2  3  6
    

    那么,对于我想要做的事情,是否有一个单行程序,而不需要遍历列?

    2 回复  |  直到 7 年前
        1
  •  4
  •   iz_    7 年前

    我想你在找 applymap . 也, lambda x: list(x) 可以简化为 list :

    In [5]: df[['a', 'b']].applymap(list)
    Out[5]:
            a          b
    0  [0, 1]     [1, 2]
    1  [1, 2]  [2, 3, 4]
    2      []        [3]
    
        2
  •  2
  •   cs95 abhishek58g    7 年前

    尝试使用嵌套列表理解来提高性能:

    pd.DataFrame([[list(l) for l in r] for r in df.values], 
                 index=df.index,
                 columns=df.columns)
    
            a          b
    0  [0, 1]     [1, 2]
    1  [1, 2]  [2, 3, 4]
    2      []        [3]
    

    在处理混合数据类型时,我完全相信纯Python的强大功能。关于什么时候循环胜过熊猫的更多信息,请看我在这里写的: For loops with pandas - When should I care?

    这种差异是显而易见的,即使是对于微小的帧:

    %timeit df[['a', 'b']].applymap(list)
    %%timeit
    pd.DataFrame([[list(l) for l in r] for r in df.values], 
                 index=df.index,
                 columns=df.columns)
    
    3.41 ms ± 92 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    669 µs ± 63.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)