Skip to main content
 首页 » 编程设计

python之Pandas DataFrame 中的行值到列数组

2024年10月24日9yxwkf

我有一个如下所示的 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 .