如何将数据帧单元格中分离的行合并到lis中

2024-10-01 22:40:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望通过将userID匹配到一个列表中来组合数据帧中的行。有1000多个用户标识,每个都有多个条目

我希望每个用户有一行。 我发现了一个线程,它的作用与我正在尝试的完全相反,即: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

以此类推


Tags: 数据no用户列表bar标识fulluserid
1条回答
网友
1楼 · 发布于 2024-10-01 22:40:25

你可以这样做:

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

相关问题 更多 >

    热门问题