如何使用csv模块统计发生率和计算评分?

2024-10-17 06:18:37 发布

您现在位置:Python中文网/ 问答频道 /正文

你有一个CSV文件的个人歌曲评级,你想知道平均评级的一首歌。该文件将包含一首歌每行1-5的评级。在

编写一个名为average_rating的函数,它接受两个字符串作为参数,其中第一个字符串表示包含歌曲分级的CSV文件的名称,格式为:“YouTubeID,artist,title,rating”,第二个参数是歌曲的YouTubeID。YouTubeID、artist和title都是字符串,而评级是1-5范围内的整数。此函数应返回输入YouTubeID的歌曲的平均评分。在

请注意,CSV文件的每一行都是来自用户的单独评分,而且每首歌可能会被多次评分。当你通读这个文件时,你需要追踪所有收视率的总和以及这首歌被评了多少次才能计算出平均收视率。(我的代码如下)

import csv
def average_rating(csvfile, ID):
    with open(csvfile) as f:
        file = csv.reader(f)
        total = 0
        total1 = 0
        total2 = 0
        for rows in file:
            for items in ID:
                if rows[0] == items[0]:
                    total = total + int(rows[3])
                    for ratings in total:
                        total1 = total1 + int(ratings)
                        total2 = total2 + 1
    return total1 / total2

输入错误['评级.csv','rh5ta6ihqq']:除以零。我该如何解决这个问题?在


Tags: 文件csv字符串infor歌曲评分rows
2条回答

您可以使用pandas DataFrame来实现这一点。在

import pandas as pd
df = pd.read_csv('filename.csv')
total_sum = df[df['YouTubeID'] == 'RH5Ta6iHhCQ'].rating.sum()
n_rating = len(df[df['YouTubeID'] == 'RH5Ta6iHhCQ'].rating)
average = total_sum/n_rating

有一些令人困惑的事情,我认为重命名变量和重构将是一个明智的决定。如果一个函数负责获取某个特定youtube id的所有行,而另一个函数则用于计算平均值,这甚至会使事情变得更加明显。在

def average_rating(csvfile, id):
    '''
    Calculate the average rating of a youtube video

    params: - csvfile: the location of the source rating file
            - id: the id of the video we want the average rating of
    '''
    total_ratings = 0
    count = 0
    with open(csvfile) as f:
        file = csv.reader(f)
        for rating in file:
            if rating[0] == id:
                count += 1
                total_ratings += rating[3]
    if count == 0:
        return 0
    return total_ratings / count

相关问题 更多 >