代码之家  ›  专栏  ›  技术社区  ›  Juan Leni

如何访问/拆分包含列表的列中的项

  •  0
  • Juan Leni  · 技术社区  · 7 年前

    假设我收到一个数据集,其结构与此类似(我知道此结构不是典型的)

    下面的代码只是生成一个看起来像我的数据的数据帧示例。

    tmp = pd.DataFrame(
        [
            {'foo': 123, 'bar': [1, 2]}, 
            {'foo': 456, 'bar': [1, 2]} 
        ] 
    )
    
    
       foo    item
    0  123  [1, 2]
    1  456  [1, 2]
    

    有没有简单的方法:

    • 访问栏中的项目。。就像df.bar[1],结果是2? (这显然不起作用)
    • 或者将bar列拆分为bar.0、bar.1等。。

    注意,栏中的列表不限于2个项目,并且数字可能会有一些变化。

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

    是的,有。使用 str.get

    tmp.bar.str.get(0)
    
    0    1
    1    1
    Name: bar, dtype: int64
    
    tmp.bar.str.get(1)
    
    0    2
    1    2
    Name: bar, dtype: int64
    

    若要拆分,请使用pandas DataFrame构造函数

    col_names = ['bar.0', 'bar.1'] # Notice you can dinamically create this if needed
    pd.DataFrame(tmp.bar.values.tolist(), columns=col_names)
    
        bar.0   bar.1
    0   1       2
    1   1       2
    
        2
  •  2
  •   sacuL    7 年前

    对于你的第二个请求,你可以申请 pd.Series ,并与原始数据帧连接:

    >>> pd.concat((tmp,tmp.bar.apply(pd.Series).add_prefix('bar_')), axis=1)
          bar  foo  bar_0  bar_1
    0  [1, 2]  123      1      2
    1  [1, 2]  456      1      2
    

    即使在 bar

    >>> tmp
             bar  foo
    0  [1, 2, 3]  123
    1     [1, 2]  456
    
    >>> pd.concat((tmp,tmp.bar.apply(pd.Series).add_prefix('bar_')), axis=1)
             bar  foo  bar_0  bar_1  bar_2
    0  [1, 2, 3]  123    1.0    2.0    3.0
    1     [1, 2]  456    1.0    2.0    NaN