Python: 将计数器附加到 csv 文件
Python: appending a counter to a csv file
我正在使用从 last.fm 收集的数据 (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]]])
我正在使用从 last.fm 收集的数据 (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]]])