【发布时间】:2018-06-15 17:51:11
【问题描述】:
有一个包含 6 列的 .csv 文件。分组是根据第 1 列的重复值进行的;对应列中的所有值(剩余 5 个)应合并为一列。 样本数据
col1 col2 col3 col4 col5 col6
1234 Some Text Reg1 Value1 Txt A
2345 Any Text Reg1 Value2 Txt B
3456 Some Text Reg2 Value3 Txt C
1234 Another Text Reg3 Value2 Txt D
下面是代码,我正在使用
import csv
import sys
if len(sys.argv) < 2:
print('To few arguments, please specify input filename')
sys.exit()
filename = sys.argv[1]
accs = {}
with open(filename, mode='rU') as f:
reader = csv.reader(f, delimiter=',')
for n, row in enumerate(reader):
if not n:
# Skip header row (n = 0).
continue
acc, res, reg, col4, col5, col6 = row
if acc not in accs:
accs[acc] = list()
accs[acc].append((res,reg,col4,col5,col6))
def listToStringWithoutBrackets(list1):
return str(list1).replace('[','').replace(']','')
with open('output.csv', 'w', newline='') as csvFile:
writer = csv.writer(csvFile)
for key, value in accs.items():
writer.writerow([key, listToStringWithoutBrackets(value)])
print("Output file, with a name Output.csv has been created in the current working directory!")
我提到了Sample Code for Group by in Python 下面是我得到的结果(因为我使用了 List 和 Key 作为 Col1 和其他列作为值)
col1 col2
1234 (Some Text,Reg1,Value1,Txt,A),(Another Text, Reg3, Value2, Txt, D)
2345 (Any Text, Reg1, Value2, Txt, B)
3456 (Some Text,Reg2,Value3, Txt,C)
预期结果(需要实际结果)
col1 col2 col3 col4 col5 col6
1234 Some Text, Another Text Reg1, Reg3 Value1, Value2 Txt, Txt A,D
2345 Any Text Reg1 Value2 Txt B
3456 Some Text Reg2 Value3 Txt C
需要不使用第 3 方库的预期(期望)结果。
任何帮助!
【问题讨论】:
-
您愿意使用 Pandas 等第三方库吗?
-
要求是不使用第三方库。
-
已记录。 已完成。
标签: python python-3.x list