import numpy as np
origin = np.arange(12).reshape(4, 3)
"""
[0 1 2
3 4 5
6 7 8
9 10 11]
"""
subset = origin[1:3, :2]
"""
[3 4
6 7]
"""
How can I get index slices [1, 2] and [0, 1] given subset and origin assuming subset are contiguous part of origin? What if it's not contiguous?
Background: I'm learning subclassing of np.ndarray, and want to and index and columns label on it (similar as pd.DataFrame but not as robust as it). When dealing with slicing by __array_finalize__ method, I have to get the index slices of self(subset) from obj(origin), and set corresponding subset of index and columns to new object.
import numpy as np
class InfoArray(np.ndarray):
def __new__(cls, input_array, index=[], columns=[]):
obj = np.asarray(input_array).view(cls)
obj.index = index
obj.columns = columns
return obj
def __array_finalize__(self, obj):
if obj is None:
return
"""
index_slice, columns_slice = get_slice(self, obj). # todo
self.index = obj.index[index_slice]
self.columns = obj.columns[columns_slice]
"""