[英]Python: appending a counter to a csv file
我正在使用從last.fm收集的data(csv)進行項目。 在數據集中有四列,第一列是藝術家,第二列是專輯,第三列是歌曲名,第四列是我將曲目划到last.fm的日期。 我已經找到一種計算每個藝術家,專輯和歌曲的出現次數的方法,但是我想將此數據附加到每個數據行,因此我將使用具有7列的csv文件。 因此,我想在每一行中添加歌曲,藝術家和專輯在數據集中的次數。 我只是不知道如何做到這一點。 我很難找到合適的藝術家。 有人可以幫忙嗎?
import csv
import collections
artists = collections.Counter()
album = collections.Counter()
song = collections.Counter()
with open('lastfm.csv') as input_file:
for row in csv.reader(input_file, delimiter=';'):
artists[row[0]] += 1
album[row[1]] += 1
song[row[2]] += 1
for row in input_file:
row[4] = artists(row[0])
假設輸入文件不是很大,您可以再次重復輸入文件,並寫出行並附加計數,如下所示:
import csv
import collections
artists = collections.Counter()
album = collections.Counter()
song = collections.Counter()
with open('lastfm.csv') as input_file:
for row in csv.reader(input_file, delimiter=';'):
artists[row[0]] += 1
album[row[1]] += 1
song[row[2]] += 1
with open('output.csv', 'w') as output_file:
writer = csv.writer(output_file, delimiter=';')
with open('lastfm.csv', 'r') as input_file:
for row in csv.reader(input_file, delimiter=';'):
writer.writerow(row + [song[row[2]], artists[row[0]], album[row[1]]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.