Sna*_*aaa 5 python csv counter dictionary
我有数据的csv文件具有列‘number’
,’colour’
,’number2’
,’foo’
,’bar’
,它看起来像:
12, red, 124, a, 15p
14, blue, 353, c, 7g
12, blue, 125, d, 65h
12, red, 124, c, 12d
Run Code Online (Sandbox Code Playgroud)
我想计算number,color和number2一起出现的次数,因此,例如,上述列表的输出为:’12, red, 124 :2’,’14, blue, 353: 1’, ’12, blue, 125: 1’
。我通过使用以下方法完成此操作:
import csv
datafile=open('myfile.csv','r')
usefuldata=[]
for line in datafile:
usefuldata.append(line)
from collections import Counter
outfile1=Counter((line[1],line[2],line[3]) for line in usefuldata)
print(outfile1)
Run Code Online (Sandbox Code Playgroud)
这给了我:
Counter({(‘12’,’red’,’135’): 21, (‘15’,’blue’,’152’):18, (‘34’,’green’,’123’):16 etc})
Run Code Online (Sandbox Code Playgroud)
很棒,但是我想将其写到文件中。我希望文件具有4列:数字,颜色,数字2和计数。我意识到这是一个常见的问题,我尝试了在其他线程上建议的几种不同方法,但没有一种起作用。
Newfile=open(‘newfile.csv’,’wb’)
fieldnames=['a','b']
csvwriter=csv.DictWriter(newfile, delimiter=',', fieldnames=fieldnames)
csvwriter.writerow(dict((fn,fn) for fn in fieldnames))
for row in outfile1:
csvwriter.writerow(row)
Run Code Online (Sandbox Code Playgroud)
和
with open('newfile.csv','wb') as csvfile:
fieldnames=['number','colour','number2']
writer=csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow(Counter((line[1],line[2],line[3]) for line in usefuldata))
countwriter=csv.writer(csvfile, delimiter=', ')
countwriter.writerow(outfile1)
Run Code Online (Sandbox Code Playgroud)
两者都给我错误
return self.writer.writerow(self._dict_to_list(rowdict))
TypeError: 'str' does not support the buffer interface
Run Code Online (Sandbox Code Playgroud)
我也试过用泡菜:
import pickle
with open('newfile.csv','wb') as outputfile:
pickle.dump(outfile1, outputfile)
Run Code Online (Sandbox Code Playgroud)
给我乱码。
我目前的尝试是使用
writer=csv.DictWriter(newfile, outfile1)
for line in outfile1:
writer.writerow(line)
Run Code Online (Sandbox Code Playgroud)
但这给我关于字段名的错误。
我知道这是一个常见的问题,我意识到自己只是在挣扎,因为我真的不知道自己在做什么-自从使用python已有好几年了,我已经忘记了很多。任何帮助将不胜感激。
首先说一下主要问题的原因——
TypeError: 'str' does not support the buffer interface
Run Code Online (Sandbox Code Playgroud)
是您以二进制模式打开文件,您应该以文本模式打开文件(不带b
)。
其次,我想说,由于您的字典的创建方式,使用普通模式csv.writer
比您的情况更容易。csv.DictWriter()
将结果写入 csv 的一种方法是 -
#Assuming you have previously created the counter you want to write
#lets say you stored the counter in a variable called cnter
with open('newfile.csv','w') as csvfile:
fieldnames=['number','colour','number2','count']
writer=csv.writer(csvfile)
writer.writerow(fieldnames)
for key, value in cnter.items():
writer.writerow(list(key) + [value])
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4543 次 |
最近记录: |