I want to make a sparse numpy array using the indexes and values stored in a pandas DataSet

The dataset has 'userIndex', 'movieIndex' and 'rating' with a million rows

For example:

-- movieIndex userIndex rating
0 0 4 2.5
1 2 2 3.0
2 1 1 4.0
3 2 0 4.0
4 4 2 3.0

Would be transformed to a numpy array like this:

[[0 0 0 0 2.5],
[0 4.0 0 0 0],
[4.0 0 3.0 0 0],
[0 0 0 0 0],
[0 0 3.0 0 0]]

So, first I'm making a np.zeros array with the correct size:

Y = np.zeros([nm,nu])

And for now, I'm passing the information as:

for i in range(len(ratings)):
  Y[int(ratings.iloc[i].movieIndex),int(ratings.iloc[i].userIndex)]
    = ratings.iloc[i].rating

And it works just fine with O(n), so it's not really bad but it takes 3 minutes to do so. I know it's not a good idea to use "for" in a dataset, and I should use the vector functions to do it, but I can't find a way to make this work. Any ideas?

推荐答案

Maybe it will work faster:

Y[ratings["movieIndex"].values, ratings["userIndex"].values] = ratings["rating"].values

Python相关问答推荐

Django mysql图标不适用于小 case

Pytest两个具有无限循环和await命令的Deliverc函数

使用miniconda创建环境的问题

Python解析整数格式说明符的规则?

如何从pandas的rame类继承并使用filepath实例化

无法连接到Keycloat服务器

如何合并两个列表,并获得每个索引值最高的列表名称?

如何在PySide/Qt QColumbnView中删除列

以逻辑方式获取自己的pyproject.toml依赖项

在不同的帧B中判断帧A中的子字符串,每个帧的大小不同

Gekko中基于时间的间隔约束

比Pandas 更好的 Select

根据客户端是否正在传输响应来更改基于Flask的API的行为

如何将一组组合框重置回无 Select tkinter?

将CSS链接到HTML文件的问题

为什么后跟inplace方法的`.rename(Columns={';b';:';b';},Copy=False)`没有更新原始数据帧?

Django.core.exceptions.SynchronousOnlyOperation您不能从异步上下文中调用它-请使用线程或SYNC_TO_ASYNC

如何从数据框列中提取特定部分并将该值填充到其他列中?

如何在Python中解析特定的文本,这些文本包含了同一行中的所有内容,

分解polars DataFrame列而不重复其他列值