在python中合并具有相同类别的csv文件行

我熟悉用python读写csv文件的基本概念.但是我坚持要为这个问题弄个逻辑.我认为GROUP BY可以解决我的问题,但如何在python中做到

Category         Data
A                Once upon a time.
A                There was a king.
A                who ruled a great and glorious nation.
B                He loved each of them dearly. 
B                One day, when the young ladies were of age to be married. 
B                terrible, three-headed dragon laid. 
C                It is so difficult to deny 
C                the reality

我想对这样的输出进行逻辑处理,即类别A的数据合并到一行,对于类别B和C则这样合并.

Category         Data
    A                Once upon a time. There was a king. who ruled a great and glorious nation.
    B                He loved each of them dearly. One day, when the young ladies were of age to be married. terrible, three-headed dragon laid. 
    C                It is so difficult to deny the reality

请大家在这个逻辑上帮助我,请多多关照.

最佳答案
使用pandas库,您可以使用groupby并创建一个自定义聚合函数,该函数将各个类别的数据连接在一起

>>> import pandas as pd
>>> data = [['A', 'Once upon a time.'], ['A', 'There was a king.'], ['A', 'who ruled a great and glorious nation.'], ['B', 'He loved each of them dearly. '], ['B', 'One day, when the young ladies were of age to be married. '], ['B', 'terrible, three-headed dragon laid. '], ['C', 'It is so difficult to deny '], ['C', 'the reality']]
>>> df = pd.DataFrame(data=data, columns=['Category','Data'])
>>> df
  Category                                               Data
0        A                                  Once upon a time.
1        A                                  There was a king.
2        A             who ruled a great and glorious nation.
3        B                     He loved each of them dearly.
4        B  One day, when the young ladies were of age to ...
5        B               terrible, three-headed dragon laid.
6        C                        It is so difficult to deny
7        C                                        the reality
>>> df.groupby('Category').agg({'Data': lambda x : ' '.join(x)})
                                                       Data
Category
A         Once upon a time. There was a king. who ruled ...
B         He loved each of them dearly.  One day, when t...
C                   It is so difficult to deny  the reality

转载注明原文:在python中合并具有相同类别的csv文件行 - 代码日志