Python Forum
Emulate slicing for a method
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Emulate slicing for a method
#1
Hi,

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.
Reply


Messages In This Thread
Emulate slicing for a method - by heras - Jul-28-2018, 09:14 PM
RE: Emulate slicing for a method - by ichabod801 - Jul-28-2018, 09:33 PM
RE: Emulate slicing for a method - by heras - Jul-28-2018, 10:00 PM
RE: Emulate slicing for a method - by volcano63 - Jul-29-2018, 02:55 PM
RE: Emulate slicing for a method - by ichabod801 - Jul-30-2018, 01:03 AM
RE: Emulate slicing for a method - by heras - Jul-30-2018, 10:36 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020