【问题标题】:How to combine separated rows in a Dataframe cell into a list [duplicate]如何将数据框单元格中的分隔行组合成列表[重复]
【发布时间】:2018-11-13 05:54:16
【问题描述】:

我希望通过将用户 ID 匹配到列表中来组合数据框中的熊猫行。每个有 1000 多个用户 ID 和多个条目。

我想为每个用户一行。 我发现了一个与我想要做的完全相反的线程,即:How to explode a list inside a Dataframe cell into separate rows 提前谢谢各位。

对于带有字符串和数字的行需要做什么?

  userID    alcohol 
  U1001     No_Alcohol_Served 7.0
            Wine-Beer 2.0
  U1002     Full_Bar 1.0
            No_Alcohol_Served 3.0
            Wine-Beer 6.0
  U1003     Full_Bar 2.0
            No_Alcohol_Served 8.0
            Wine-Beer 3.0
  U1004    No_Alcohol_Served 4.0
           Wine-Beer 4.0

我想说的是:

U1001 : No_Alcohol_served:7.0, Wine-Beer:2.0
U1002 : Full_Bar:1.0, No_Alcohol_served:3.0, Wine_beer:6.0

以此类推

【问题讨论】:

标签: python pandas dataframe


【解决方案1】:

你可以试试这样的:

df.groupby('userID').apply(lambda x: x['name'].tolist())

示例:

给定一个df

  userID name
0  U1001    a
1  U1001    b
2  U1001    c
3  U1002    d
4  U1002    e
5  U1003    f

>>> df.groupby('userID').apply(lambda x: x['name'].tolist())
userID
U1001    [a, b, c]
U1002       [d, e]
U1003          [f]
dtype: object

【讨论】:

  • 谢谢!我将如何进行第 2 部分?我刚刚编辑了它。谢谢
  • 您可以将您的数据框作为文本发布吗?否则无法为您提供帮助。
  • 更新了!很抱歉给您带来不便
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 2018-08-12
  • 2018-09-24
  • 2018-08-06
  • 2019-07-12
  • 2010-10-02
  • 1970-01-01
相关资源
最近更新 更多