【问题标题】:Python: appending a counter to a csv filePython:将计数器附加到 csv 文件
【发布时间】:2016-03-12 06:20:18
【问题描述】:

我正在使用从 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])

【问题讨论】:

  • 也许看看csv.writer
  • 好的,我知道这对我有什么帮助,但是我如何从正确行的 collections.counter 中获取正确的数据(这样我才能在正确的艺术家那里获得正确的艺术家数)?跨度>
  • 我觉得应该这样称呼:artists[row[0]]

标签: python csv append


【解决方案1】:

假设输入文件不是很大,您可以再次重复输入文件并写出附加计数的行,如下所示:

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

【讨论】:

  • 哇,这正是我想要的。非常感谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-21
  • 1970-01-01
  • 2019-03-26
  • 2020-12-26
  • 1970-01-01
  • 2015-12-13
相关资源
最近更新 更多