2017-04-12 38 views
0

有一個問題,即將重複鍵的多個值合計爲一個鍵與總合計。例如: 1:5 2:4 3:2 1:4 非常基本的,但我正在尋找看起來輸出像: 1:9 2:4 3:2將一列中的值與另一個列中的相應值彙總在兩個文件中

在我使用的兩個文件中,我正在處理具有artistID(第2列)的51個用戶(user_artists.dat的第1列)的列表以及該用戶聽過該特定藝術家的重量(第3欄)。

我試圖聚合藝術家在所有用戶中播放的總時間,並以如下格式顯示它: Britney Spears(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) 

回答

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 
+0

嗨!感謝您的迴應,'物品'沒有定義?我一直在試圖弄清楚它應該是什麼樣的,或者它應該如何被初始化,而不能讓它起作用。 – pythonuser890

+0

是啊,對不起,這是一個我打算打印的錯字「.iteritems()」最後寫了「.iter(items)」 –

+0

謝謝!現在正在閱讀:artist_repo = dict(x.strip()。split('\ t')[:: - 1] for x in artists [1:]) ValueError:字典更新順序元素#0的長度爲4; 2是必需的。沒關係!非常感謝。 – pythonuser890

相關問題