我有一个.dat文件,它包含三列-userID,artistID和weight。 将数据读入Python数据帧pd.read U表格('列车日期')。在
我想创建一个稀疏矩阵(/2D array),它将数据帧的前两列('userID,'artistID)的值作为索引,第三列作为值('weight)。 数据帧中未给出的索引组合应为NaN。在
我尝试创建一个空的numpy数组并使用for循环填充它,但这需要很多时间(大约有100k行在其中)列车日期). 在
import csv
import numpy as np
f = open("train.dat", "rt")
reader = csv.reader(f, delimiter="\t")
next(reader)
data = [d for d in reader]
f.close()
data = np.array(data, dtype=float)
col = int(a[:,0].max()) + 1
row = int(a[:,1].max()) + 1
empty = np.empty((row, col))
empty[:] = np.nan
for d in data:
empty[int(d[0]), int(d[1])] = d[2]
还尝试创建一个coo_矩阵并将其转换为csr_矩阵(这样我就可以使用索引访问数据),但是索引重置了。在
^{pr2}$数据示例:
userID artistID weight
45 7 0.7114779874213837
204 144 0.46399999999999997
36 650 2.4232887490165225
140 146 1.0146699266503667
170 31 1.4124783362218372
240 468 0.6529992406985573
将数据复制到文件:
我还可以使用
^{pr2}$genfromtxt
加载该文件:相关问题 更多 >
编程相关推荐