Peque
Peque

Reputation: 14811

Python Pandas: Adding methods to class pandas.core.series.Series

I want to work with a time series in Python and, therefore, Pandas' Series class is just perfect and has a lot of useful methods.

Now I want to add some methods that I need and are not implemented. For example, let us say I am interested in adding a method which appends two times one value to the time series, at let us call that method append2:

import pandas                                                                         
import random                                                                         

class Testclass(pandas.core.series.Series):                                           
        def append2(self, val):                                                       
                return self.append(val).append(val)                                   

dates = pandas.date_range('1/1/2011', periods=72, freq='H')                           
data = [random.randint(20, 100) for x in range(len(dates))]                           
ts = pandas.Series(data, index=dates)                                                 

a = Testclass()                                                                       
b = a.append2(ts[[1]])                                                                

print type(a)                                                                         
print type(b)

Now I find that the class of a and the class of b are different; b is a pandas.core.series.Series object and therefore you can not apply the method append2 to it.

I would like b to conserve the append2 method (conserve the same class as a). Is that possible? Is there any other way to add methods to the Series class without modifying the source code of the Pandas package?

Upvotes: 3

Views: 2200

Answers (1)

Jeff
Jeff

Reputation: 128958

You could do something like this. You don't need to sub-class at all, rather just monkey-patch. And this would be more efficient that appending twice (as an append copies).

In [5]: s = Series(np.arange(5))

In [15]: def append2(self, val):
   ....:     if not isinstance(val, Series):
   ....:         val = Series(val)
   ....:     return concat([ self, val, val ])
   ....: 

In [16]: Series.append2 = append2

In [17]: s.append2(3)
Out[17]: 
0    0
1    1
2    2
3    3
4    4
0    3
0    3
dtype: int64

Upvotes: 8

Related Questions