首页 > 解决方案 > 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 的位置可以是可变的,我以它为例)

标签: pythonpandasnumpy

解决方案


正如您用 标记问题一样pandas,这是使用str.get_dummiespandas 方法解决问题的一种方法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]])

推荐阅读