簡體   English   中英

如何遍歷數據框

[英]How to iterate over a data frame

我有一個用戶、書籍和評分的數據集,我想找到對特定書籍評分高的用戶,對於這些用戶,我也想找到他們喜歡的其他書籍。

我的數據看起來像:

df.sample(5)

    User-ID     ISBN    Book-Rating
49064   102967  0449244741  8
60600   251150  0452264464  9
376698  52853   0373710720  7
454056  224764  0590416413  7
54148   25409   0312421273  9

我到目前為止:

df_p = df.pivot_table(index='ISBN', columns='User-ID', values='Book-Rating').fillna(0)
lotr = df_p.ix['0345339703'] # Lord of the Rings Part 1
like_lotr = lotr[lotr > 7].to_frame()
users = like_lotr['User-ID']

最后一行失敗

KeyError: '用戶 ID'

我想獲得那些評分為 LOTR > 7 的用戶,進一步從矩陣中找到他們也喜歡的電影。

幫助將不勝感激。 謝謝。

在您的like_lotr數據like_lotr 'User-ID'是索引的名稱,您不能像普通列一樣選擇它。 這就是為什么線users = like_lotr['User-ID']提出了一個KeyError 它不是一個列。

此外ix已棄用,最好在您的情況下使用loc 並且不要加引號:它必須是一個整數,因為'User-ID'最初是一列整數(至少來自您的示例)。

像這樣嘗試:

df_p = df.pivot_table(index='ISBN', columns='User-ID', values='Book-Rating').fillna(0)
lotr = df_p.loc[452264464] # used another number from your sample dataframe to test this code.
like_lotr = lotr[lotr > 7].to_frame()
users = like_lotr.index.tolist()

user現在是一個包含您想要的 ID 的列表。

使用上面的小樣本和我用來測試的數字, user[251150]


另一種解決方案是使用reset_index 最后兩行應該是這樣的:

like_lotr = lotr[lotr > 7].to_frame().reset_index()
users = like_lotr['User-ID']

reset_index將索引放回列中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM