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

时间:2017-04-12 21:52:42

标签: python pandas data-analysis defaultdict bigdata

有一个问题,即将重复键的多个值合计为一个具有总计的键。例如: 1:5 2:4 3:2 1:4 非常基本,但我正在寻找一个看起来像这样的输出: 1:9 2:4 3:2

在我使用的两个文件中,我正在处理51个用户(user_artists.dat的第1列)的列表,这些用户具有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)

1 个答案:

答案 0 :(得分:0)

怎么样:

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