python - Python 索引错误 - 轴 0 越界
问题描述
我在 txt 文件中有如下数据集。(第一列=userid,第二列=locationid)通常我的数据集很大,但我创建了一个虚拟数据集来更好地解释我的问题。
我正在尝试创建一个矩阵,如下面的代码所示。行将是用户 ID 列位置 ID。由于该数据集显示了用户访问的位置 ID,因此我将代码中的值 1 分配给他们在矩阵中访问的位置。
我收到一个索引错误。IndexError: index 801 is out of bounds for axis 0 with size 50
我尝试了不同的 user_num 和 poi_num 但仍然不起作用
数据用户.txt
801 32332
801 14470
801 33847
501 10259
501 34041
501 10201
301 15810
301 34827
301 19264
401 34834
401 35407
401 36115
代码
import numpy as np
from collections import defaultdict
from itertools import islice
import pandas as pd
train_file = "datausers.txt"
user_num = 20
poi_num = 20
training_matrix = np.zeros((user_num, poi_num))
train_data = list(islice(open(train_file, 'r'), 10))
for eachline in train_data:
uid, lid= eachline.strip().split()
uid, lid = int(uid), int(lid)
training_matrix[uid, lid] = 1.0
错误
预期产出
4x12 矩阵,因为我们有 4 个唯一用户和 12 个唯一位置
[1 0 1 0 1 0 0 0 0 0 0 0
0 1 0 1 0 1 0 0 0 0 0 0
...
]
例如对于第一行 1 0 1 0 1 0 0 0 0 0 0 0
用户 801 访问了 3 个位置,它们是 1。(1 的位置可以是可变的,我以它为例)
解决方案
正如您用 标记问题一样pandas
,这是使用str.get_dummies
pandas 方法解决问题的一种方法Series
:
df = pd.read_csv('datausers.txt', sep='\s+', names=['userid', 'locationid'], index_col=0)
out = df['locationid'].astype(str).str.get_dummies().sum(level=0)
结果
对于样本数据
>>> out
10201 10259 14470 15810 19264 32332 33847 34041 34827 34834 35407 36115
userid
801 0 0 1 0 0 1 1 0 0 0 0 0
501 1 1 0 0 0 0 0 1 0 0 0 0
301 0 0 0 1 1 0 0 0 1 0 0 0
401 0 0 0 0 0 0 0 0 0 1 1 1
如果您需要numpy
数组:
>>> out.to_numpy()
array([[0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]])
推荐阅读
- java - 从使用术语@Service 或@Controller 注释的单例类创建的对象如何在Spring 中并行化?
- graphics - 如何在 DirectX 11 中进行静态环境映射?
- flutter - IconData 没有作为参数传递给类实例化
- php - PHP - 使用路由库我需要了解哪些 PHP 路由概念?
- javascript - 有没有办法显示溢出其父元素的 ul 元素的最后一个 li 元素?
- laravel - 调用关系后访问目标表的列 - Laravel
- angular - 使用behavioursubject调用组件的方法
- python - npyscreen 动态更改小部件的值
- javascript - 将数组转换为对象而不在javascript中对键进行排序
- lua - Roblox Studio 错误:Workspace.Driver.OnSeated!:13:尝试使用“名称”索引 nil