2018-10-23
閱讀量:
1161
如何建立稀疏矩陣?
在python第三方庫(kù)中,直接導(dǎo)入調(diào)用 lil_matrix,即可建立稀疏矩陣。(以電影評(píng)分為例)
lil_matrix是使用兩個(gè)列表存儲(chǔ)非0元素。data保存每行中的非零元素,rows保存非零元素所在的列。這種格式也很適合逐個(gè)添加元素,并且能快速獲取行相關(guān)的數(shù)據(jù)。
#建立用戶-電影 評(píng)分稀疏矩陣
from scipy.sparse import lil_matrix
row_count=len(list(table.groupby("user_id")))
# col_count=len(list(movies.groupby("m_id")))
row_count
ratings=table.loc[:,"ratings"].values
len(ratings)
col_count=a[len(a)-1]
col_count
user_row=table.loc[:,"user_id"].values
print(user_row)
print(len(user_row))
#print(user_row[1193])
movie_col=table.loc[:,"m_id"].values
print(movie_col)
len(ratings)
#user_row=table.loc[:,"user_id"].values
#movie_col=table.loc[:,"m_id"].values
user_movie=lil_matrix((row_count,col_count))
print(user_movie.toarray())
for i in range(len(user_row)):
user_movie[user_row[i]-1,movie_col[i]-1]=ratings[i]
# print(user_movie[user_row[i]-1,movie_col[i]-1])
# print("##")
#print(len(user_movie))
print(user_movie.toarray())
print(type(user_movie))
user_movie_index_cols=range(1,3953)
user_movie_index_rows=range(1,6041)
type(user_movie)
user_movie=user_movie.toarray()
user_movie
#user_movie=np.array(user_movie)
#user_movie
user_movie=pd.DataFrame(user_movie)
user_movie.head()
user_movie.index=range(1,len(user_movie)+1)
user_movie.head()
#用戶對(duì)電影的評(píng)分
user_movie.columns=range(1,3953)
user_movie.head()
輸出結(jié)果:







評(píng)論(0)


暫無(wú)數(shù)據(jù)
CDA考試動(dòng)態(tài)
CDA報(bào)考指南
推薦帖子
0條評(píng)論
0條評(píng)論
0條評(píng)論