我熟悉在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
如果你们中的任何人能够帮助我解决这个问题,我将非常感谢他的努力。
答案 0 :(得分:2)
使用pandas
库,您可以使用groupby
并制作一个自定义聚合函数,该函数只是连接每个类别Data
>>> 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
答案 1 :(得分:1)
itertools.groupby
可以提供帮助(假设第一行中的字母已订购):
from itertools import groupby
from io import StringIO
text = '''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
'''
with StringIO(text) as file:
next(file) # skip header
rows = (row.split(' ') for row in file)
for key, items in groupby(rows, key=lambda x: x[0]):
phrases = (item[1].strip() for item in items)
print(key, ' '.join(phrases))
给出:
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
如果您的数据位于文件中,则必须将上面的with StringIO(text) as file:
替换为:
with('textfile.txt') as file:
# do stuff as above with file