我有以下形式的数据框
user_id item_id rating
1 abc 5
1 abcd 3
2 abc 3
2 fgh 5
我想将其转换为 numpy 矩阵,例如
# abc abcd fgh
[[5, 3, 0] # user_id 1
[3, 0, 5]] # user_id 2
有人可以帮忙吗?
最佳答案
您可以使用pivot
与 fillna
,转换为 int
并最后通过 values
转换为数组:
arr = df.pivot('user_id', 'item_id', 'rating').fillna(0).astype(int).values
print (arr)
[[5 3 0]
[3 0 5]]
另一个解决方案 set_index
, unstack
和 values
:
arr = df.set_index(['user_id','item_id']).unstack(fill_value=0).values
print (arr)
[[5 3 0]
[3 0 5]]
关于python - 将数据帧转换为 numpy 矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40918424/