我有一个numpy数组,想知道是否可以用自定义的数字序列修改索引值(而不是数组值)。
假设数组长度为10,可以更改索引,以便不使用索引0-9访问其元素,而是使用50-59进行访问?
基本上像在pandas df中更改rownames / colnames一样,在np数组中进行更改。
假设数组长度为10,可以更改索引,以便不使用索引0-9访问其元素,而是使用50-59进行访问?
基本上像在pandas df中更改rownames / colnames一样,在np数组中进行更改。
不确定是否需要这样做,我相信还有其他方法,但一种方法是创建一个类。以50-59为例:
class UnnaturalList(list):
def __getitem__(self, index):
if type(index) == int and index > 0:
index -= 50
if type(index) == slice:
start, stop = index.start, index.stop
if start and start > 0:
start -= 50
if stop and stop > 0:
stop -= 50
index = slice(start, stop, index.step)
return super().__getitem__(index)
def __setitem__(self, index, val):
super().__setitem__(index - 50, val)
a_list = UnnaturalList(range(1,6))
a_list --> [1,2,3,4,5]
a_list[50] --> 1
a_list[51] --> 2
a_list[50:53] --> [1,2,3]
我认为有一种类似于这种方法的方式可以用于数组,或者更加简洁的方法,但是这是其中一种可以供你使用的方法。
numpy
数组没有行/列名称。索引严格按照从 0 开始计数的方式进行。 - hpaulj