我有一个Pandas数据帧,看起来像这样:
+---+--------+-------------+------------------+
| | ItemID | Description | Feedback |
+---+--------+-------------+------------------+
| 0 | 8988 | Tall Chair | I hated it |
+---+--------+-------------+------------------+
| 1 | 8988 | Tall Chair | Best chair ever |
+---+--------+-------------+------------------+
| 2 | 6547 | Big Pillow | Soft and amazing |
+---+--------+-------------+------------------+
| 3 | 6547 | Big Pillow | Horrific color |
+---+--------+-------------+------------------+
我想将"反馈"列中的值连接到一个新列中,用逗号分隔,其中 ItemID 匹配。这样:
+---+--------+-------------+----------------------------------+
| | ItemID | Description | NewColumn |
+---+--------+-------------+----------------------------------+
| 0 | 8988 | Tall Chair | I hated it, Best chair ever |
+---+--------+-------------+----------------------------------+
| 1 | 6547 | Big Pillow | Soft and amazing, Horrific color |
+---+--------+-------------+----------------------------------+
我已经尝试了枢轴、合并、堆叠等的几种变体,但卡住了。
我认为NewColumn最终会成为一个数组,但我对Python相当陌生,所以我不确定。
此外,最终,我将尝试将其用于文本分类(对于新的"描述"生成一些"反馈"标签[多类问题])
在数据帧上调用.groupby('ItemID')
,然后连接反馈列:
df.groupby('ItemID')['Feedback'].apply(lambda x: ', '.join(x))
请参阅 Pandas groupby: How to get a union of strings。
我认为您可以按列ItemID
和Description
、apply
join
和最后reset_index
groupby
:
print df.groupby(['ItemID', 'Description'])['Feedback'].apply(', '.join).reset_index(name='NewColumn')
ItemID Description NewColumn
0 6547 Big Pillow Soft and amazing, Horrific color
1 8988 Tall Chair I hated it, Best chair ever
如果您不需要Description
列:
print df.groupby(['ItemID'])['Feedback'].apply(', '.join).reset_index(name='NewColumn')
ItemID NewColumn
0 6547 Soft and amazing, Horrific color
1 8988 I hated it, Best chair ever