Jorism
Jorism

Reputation: 25

Python: appending a counter to a csv file

I am working on a project with data(csv) i gathered from last.fm. In the dataset there are four columns, the first is the artist, second the album, the 3th is the songname and the fourth is the date at which i scrobbled the track to last.fm. I already have found a way of counting the number of occurences of each artist, album and song, but i would like to append this data to each data row so i would and up with an csv file that has 7 columns. So in each row i want to add the number of times that the song, artist and album are in the dataset. I just cannot figure out how to do this. I have a hard time to get the right artist out of the counter. Can someone help?

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])

Upvotes: 0

Views: 249

Answers (1)

JCVanHamme
JCVanHamme

Reputation: 1050

Assuming that the input file isn't enormous, you can just reiterate over your input file a second time and write the lines out with the counts appended, like so:

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]]])

Upvotes: 1

Related Questions