在数据帧列中追加值

2024-03-28 14:56:00 发布

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

你好,我是新来熊猫,我手头有一个情况,我有数据帧 例如:

我想在dataframe中添加另一列,如下所示:

enter image description here

有人能帮忙吗。我尝试过将其转换为字典和打印值,但这并不能提供这种形式的输出。你知道吗


Tags: 数据imagedataframe字典here情况description形式
1条回答
网友
1楼 · 发布于 2024-03-28 14:56:00

我认为需要^{}joined值作为string的新列:

df['col 5'] = (df.groupby(['col 1','col 2','col 3'])['col 4']
                 .transform(lambda x: ','.join(x.astype(str))))
print (df)
  col 1 col 2 col 3  col 4        col 5
0     A     B     C     25  25,22,23,45
1     A     B     C     22  25,22,23,45
2     A     B     C     23  25,22,23,45
3     A     B     C     45  25,22,23,45
4     P     Q     R      9     9,109,20
5     P     Q     R    109     9,109,20
6     P     Q     R     20     9,109,20

如果需要list使用^{}

df = df.join(df.groupby(['col 1','col 2','col 3'])['col 4']
               .apply(list).rename('col 5'), on=['col 1','col 2','col 3'])
print (df)
  col 1 col 2 col 3  col 4             col 5
0     A     B     C     25  [25, 22, 23, 45]
1     A     B     C     22  [25, 22, 23, 45]
2     A     B     C     23  [25, 22, 23, 45]
3     A     B     C     45  [25, 22, 23, 45]
4     P     Q     R      9      [9, 109, 20]
5     P     Q     R    109      [9, 109, 20]
6     P     Q     R     20      [9, 109, 20]

相关问题 更多 >