【问题标题】:Python - create a class as index for 2-dimension numpy arrayPython - 创建一个类作为二维 numpy 数组的索引
【发布时间】:2021-08-04 12:38:27
【问题描述】:

我有一些索引类代码TwoDimIndex。我想用它来索引像arr[idx]这样的numpy二维数组。下面是该类的代码。

import numpy as np

class TwoDimIndex:
    def __init__(self, i1, i2):
        self.i1 = i1
        self.i2 = i2
        pass

    def __index__(self):
        return self.i1, self.i2 
        # return np.array([self.i1, self.i2]) - Tried this too
        
    def __eq__(self, other):
        return self.i1 == other
        
    def __int__(self):
        return self.i1
        
    def __hash__(self):
        return hash(self.__int__())

# Don't edit code of this function please
def useful_func():
    idx = TwoDimIndex(1, 1) # Can edit create instance
    arr_two_dim = np.array([[0, 1], [2, 3]])
    print(idx.__index__() == (1, 1))
    print(arr_two_dim[1, 1], arr_two_dim[idx.__index__()]) # Success
    print(arr_two_dim[idx]) # Crash here
    # But I want this code work!!!

useful_func()

TwoDimIndex用作索引,例如arr[TwoDimIndex()]

Jupyter Notebook 和 Python 3.8 的所有代码。但是执行此代码时出现错误。

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

有什么方法可以让 TwoDimIndex 类的实例成为一个 numpy 二维数组索引?

【问题讨论】:

  • 你能提供一个最小的例子吗?
  • 你好。如果您使用我的代码,您将获得最少的示例。我想工作print(arr_two_dim[idx])代码。
  • idx = np.s_[ 1, 1 ] 在 numpy 数组的前 2 个维度中创建切片,但 idx = ( 1, 1 ) 也适用于整数切片值。
  • 我想拥有我自己的类的实例,而不是拥有部分 useful_func 的版本。

标签: python-3.x numpy class indexing jupyter


【解决方案1】:

我找到了从元组继承的简短解决方案。

class TwoDimIndex(tuple):
    def __init__(self, tup):
        self.tup = tuple(tup)
        pass

    def __index__(self):
        return self.tup

def useful_func():
    idx = TwoDimIndex([1, 1]) # Edit at create class
    arr_two_dim = np.array([[0, 1], [2, 3]])
    print(idx.__index__() == (1, 1))
    print(arr_two_dim[1, 1], arr_two_dim[idx.__index__()]) # Success
    print(arr_two_dim[idx]) # Success now

useful_func()

不确定它是否正确,但它有效。

【讨论】:

  • 我以前没有看到有人尝试过这个,不知道你为什么想要它。但正如您所发现的,索引与对象的性质有关。它需要是一个元组,并且包含 IndexingError 中列出的元素。 np.lib.intex_tricks 中的类(例如np.s_)给出了如何处理索引表达式的概念。
猜你喜欢
  • 2023-01-04
  • 2012-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-01
  • 2016-10-27
相关资源
最近更新 更多