将两个文件中一列中的值与其在另一列中对应的值进行聚合

2024-04-27 04:17:42 发布

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

有一个关于将重复键的多个值相加为一个键的总和的问题。例如: 1:5 2:4 3:2 1:4 非常基本,但我要找的输出如下所示: 1:9 2:4 比例3:2

在我使用的两个文件中,我处理的是51个用户的列表(用户列表的第1列)_艺术家.dat)谁拥有artistID(第2列)以及用户听了该特定艺术家的多少次(第3列)。你知道吗

我正在尝试汇总所有用户播放艺术家的总时间,并以如下格式显示: 小甜甜布兰妮(289)2393140。任何帮助或意见都将不胜感激。你知道吗

import codecs
#from collections import defaultdict

with codecs.open("artists.dat", encoding = "utf-8") as f:
    artists = f.readlines()


with codecs.open("user_artists.dat", encoding = "utf-8") as f:
    users = f.readlines()


artist_list = [x.strip().split('\t') for x in artists][1:]
user_stats_list = [x.strip().split('\t') for x in users][1:]

artists = {}
for a in artist_list:
    artistID, name = a[0], a[1]
    artists[artistID] = name

grouped_user_stats = {}
for u in user_stats_list:
    userID, artistID, weight = u
    grouped_user_stats[artistID] = grouped_user_stats[artistID].astype(int)
    grouped_user_stats[weight] = grouped_user_stats[weight].astype(int)
    for artistID, weight in u:
        grouped_user_stats.groupby('artistID')['weight'].sum()
        print(grouped_user_stats.groupby('artistID')['weight'].sum())



    #if userID not in grouped_user_stats:
        #grouped_user_stats[userID] = { artistID: {'name': artists[artistID], 'plays': 1} }
    #else:
        #if artistID not in grouped_user_stats[userID]:
            #grouped_user_stats[userID][artistID] = {'name': artists[artistID], 'plays': 1}
        #else:
            #grouped_user_stats[userID][artistID]['plays'] += 1
            #print('this never happens') 




#print(grouped_user_stats)

Tags: 用户nameinforstatslistdat艺术家
1条回答
网友
1楼 · 发布于 2024-04-27 04:17:42

怎么样:

import codecs
from collections import defaultdict
# read stuff
with codecs.open("artists.dat", encoding = "utf-8") as f:
    artists = f.readlines()
with codecs.open("user_artists.dat", encoding = "utf-8") as f:
    users = f.readlines()
# transform artist data in a dict with "artist id" as key and "artist name" as value
artist_repo = dict(x.strip().split('\t')[:2] for x in artists[1:])

user_stats_list = [x.strip().split('\t') for x in users][1:]

grouped_user_stats = defaultdict(lambda:0)

for u in user_stats_list:
    #userID, artistID, weight = u
    grouped_user_stats[u[0]] += int(u[2]) # accumulate weights in a dict with artist id as key and sum of wights as values
# extra: "fancying" the data transforming the keys of the dict in "<artist name> (artist id)" format 
grouped_user_stats = dict(("%s (%s)" % (artist_repo.get(k,"Unknown artist"), k), v) for k ,v in grouped_user_stats.iteritems() )
# lastly print it
for k, v in grouped_user_stats.iteritems():
   print k,v 

相关问题 更多 >