python - 将数据帧转换为 numpy 矩阵

标签 python python-3.x pandas numpy dataframe

我有以下形式的数据框

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

有人可以帮忙吗?

最佳答案

您可以使用pivotfillna ,转换为 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 , unstackvalues :

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/

相关文章:

python - Try 和 except 都在被另一个函数调用时执行

python - 根本无法启动 Jupyter Notebook

python-3.x - 如何在 Gtk.TextView 中设置占位符文本

python-3.x - 无法构建 pyarrow(对于 python 3.7),错误消息为 ERROR : Could not build wheels for pyarrow which use PEP 517

python - 在 PyCharm 的内置控制台中获得更广泛的输出

python - 根据 Pandas 中的模式复制 Dataframe 中的行

python - pygame Sprite 和 pygame.display.flip() 导致工件

python - 将元组组合成列表

python - 有没有办法在 python pandas 中通过操作来对一组进行逆运算?

python - Pycharm:如何为外部对象类型设置自定义字符串函数(即Type Renderer)?