Pandas adding method does not survive serialization
<p>I am trying to add a method to pandas so that I can use it readily if I have access to the dataframe. However serialization "kills" the method such as shown by the following example</p>

<pre><code>import dill

class Foo:
    def sayhello(self):
        print("hello")

f = Foo()
dill.dump(f, open("./foo.pickle", "wb"))

f1 = dill.load(open("./foo.pickle", "r"))
f1.sayhello()

def addto(instance):
    def decorator(f):
        import types
        f = types.MethodType(f, instance, instance.__class__)
        setattr(instance, f.func_name, f)
        return f
    return decorator

@addto(f)
def saygoodbye(self):
    print("goodbye")

dill.dump(f, open("./foo.pickle", "wb"))

f1 = dill.load(open("./foo.pickle", "r"))

f1.sayhello()
f1.saygoodbye()

import pandas as pd

df = pd.DataFrame([0,1])
@addto(df)
def saygoodbye(self):
    print("goodbye")

dill.dump(df, open("./dframe.pickle", "wb"))
df1 = dill.load(open("./dframe.pickle", "r"))
df1.saygoodbye()
</code></pre>

<p>which throws me a <code>AttributeError: 'DataFrame' object has no attribute 'saygoodbye'</code></p>

<p>1) Do you see what is causing a problem ?</p>

<p>2) Do you have any idea how to serialize an added method on a dataframe ? </p>

<p>Thanks</p>

<p>1) Do you see what is causing a problem ?</p>

<p>You need to add the method to the class instead of the instance like</p>

<pre><code>df = pd.DataFrame([0,1])
@addto(pd.DataFrame)
def saygoodbye(self):
    print("goodbye")
</code></pre>

<p>2) Do you have any idea how to serialize an added method on a dataframe ?</p>

<p>If I understood correctly, you want to serialize the dataframe instance to a pickle file and later deserialize it later.
My suggestion is creating an new class inheriting from DataFrame.</p>

<pre><code>class MyDataFrame(pd.DataFrame):
    def saygoodbye(self):
        print 'saygoodbye'

df = MyDataFrame([0,1])
dill.dump(df, open("./dframe.pickle", "wb"))
df1 = dill.load(open("./dframe.pickle", "r"))
df.saygoodbye()
</code></pre>

python python-3.x pandas methods dill