mercredi 19 avril 2017

Python - how to implement a custom class compatible with NumPy functions?

I am trying to implement my own custom class to store data. I want to make it compatible with NumPy, so that I can call NumPy functions on it like this:

np.sin(my_object)

I know that there is a dictionary called array_interface, however I am getting lots of strange errors when trying to use it.

import numpy as np
import pandas as pd

class TDF:
    __array_interface__ = {'typestr': '|i1', 'version': 1}

    def __init__(self):
        self.ddata = pd.DataFrame([1, 2, 3])
        self.shape = self.ddata.shape

    def __iter__(self):
        return iter(self.ddata)

    def __len__(self):
        return len(self.ddata)

    def __getitem__(self, key):
        return self.ddata.__getitem__(key)

if __name__ == '__main__':
    tdf1 = TDF()
    tdf = np.sin(tdf1)

The code above gives me a run-time error:

ValueError: setting an array element with a sequence.

What am I missing? On the other hand the source code for pandas (which classes are NumPy compatible) does not explicitly use the array_interface dict...






Comments
0 Comments

0 commentaires:

Enregistrer un commentaire