【问题标题】:Groupby id a column that contains listsGroupby id 包含列表的列
【发布时间】:2022-10-12 23:19:52
【问题描述】:

假设您有以下数据框:

>>> df = pd.DataFrame({'id':[0,0,1], 'lst':[["a", "b", "c"],["e"],["c"]]})
>>> df
  id         lst
0   0  [a, b, c]
1   0        [e]
2   1        [c]

您希望按 id 对数据进行分组,如下所示:

   id        lst
0   0  [[a, b, c], [e]]
2   1  [[c]]

有没有办法对列表的列进行分组,所以可以获得我上面给出的结果?

我尝试了以下链接中发布的解决方案:Group operations on Pandas column containing lists,但它对我不起作用。

【问题讨论】:

    标签: pandas python-3.8


    【解决方案1】:

    这是一种方法

    # groupby id, then then apply list to the resulting grouped lst items
    
    df.groupby('id')['lst'].apply(list).reset_index()
    
    
        id  lst
    0   0   [[a, b, c], [e]]
    1   1   [[c]]
    

    【讨论】:

    • @AndresPerez,不关注你。我使用了您共享的数据并获得了与预期结果相匹配的结果。你的意思是拿到桌子?
    猜你喜欢
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多