Jul-28-2018, 09:14 PM
Hi,
Is there a way to make a method sliceable? For example:
Here's what I've got:
Thanks in advance.
Is there a way to make a method sliceable? For example:
my_instance.look_up[3:6]Pandas has the DataFrame class. It needs to make a new copy if you add data, perhaps because it uses an ndarray internally? I don't know. But I want to add data continuously and not have the copies so I'm trying to create a class similar to pandas.DataFrame using dict+lists. DataFrame has a method DataFrame.loc that accepts slice notation which I would like to have too.
Here's what I've got:
#!/usr/bin/env python3 class DataFrame: def __init__(self, max_frame_length): self.max_frame_length = max_frame_length self.data = {} def __getitem__(self, key): print('__getitem__', key) def add_data(self, label, value): if not label in self.data: self.data[label] = [value] else: self.data[label].append(value) def loc(self, key): print('loc', key) fname = 'smallset.txt' def read_line(fname): with open(fname) as f: for i, line in enumerate(f): a, b, c = line.split(';') data = [float(item) for item in [a, b, c]] yield i, data foo = DataFrame(200) for i, data in read_line(fname): a, b, c = stick foo.add_data('index', i) foo.add_data('a', a) foo.add_data('b', b) foo.add_data('c', c) # This works foo[1:2] # This doesn't foo.loc[1:2]I think I need to use __getitem__ somehow but I don't know how to pass the slice to the method. Any ideas?
Thanks in advance.