3

I have a numpy array, and i want see if it's possible to modify the index values (not the array values) with a custom sequence of numbers.

Let's say the array lengh is 10, it's possible to change the indexes so instead of accessing it's elements with the indexes 0-9 it can be accesed with.. let's say.. 50-59?

Basically like changing the rownames/colnames but in a np array instead of a pandas df.

2
  • Check stackoverflow.com/a/10378515/15032126, I would expect the same for numpy arrays. Commented May 27, 2022 at 17:38
  • numpy arrays don't have row/col names. Indices are strictly by count starting with 0. Commented May 27, 2022 at 19:47

1 Answer 1

2

Not sure if there is ever a need for it and I'm sure there are other ways but one way would be to create a class for it. Working on your example of 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)

Then you can create a list with this class and use indexing and slicing

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]

I would think there is a way to do something similar for arrays, or something cleaner, but this is one method for you.

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, i saw the linked question up there and it seems wrapping it into another class is the only way. Thanks anyway!
Sorry wrong post

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.