0

I want to create a new class that allows me to create pandas Series objects that are restricted so the user only needs to enter a start date and number of periods to initialize the series. I also want to be able to replace values given a date within that series. I made an attempt below but I'm getting

AttributeError: can't set attribute

When I try to assign the Series.values as shown below. How can I create my class by inheriting from Series like this?

import pandas as pd
import numpy as np

class TimeSeries(Series):
def __init__(self, start_date='1/1/2019', periods=365):
    Series.__init__(self)
    self.range = pd.date_range(start_date, periods=periods, freq='D')
    self.values = pd.Series(np.zeros(len(self.range)), index=self.range)

def set_value(self, at_date, value):
    self.values[at_date] = value
JasonArg123
  • 188
  • 1
  • 1
  • 14

1 Answers1

1

There are very few cases where actually subclassing pandas objects is necessary. This isn't one of them. Why not use the date_range function and promote to Series?

pd.date_range('1/1/2019', periods=365, freq='D').to_series()

2019-01-01   2019-01-01
2019-01-02   2019-01-02
2019-01-03   2019-01-03
2019-01-04   2019-01-04
2019-01-05   2019-01-05

pd.Series(0, index=pd.date_range('1/1/2019', periods=365, freq='D'))

2019-01-01    0
2019-01-02    0
2019-01-03    0
2019-01-04    0
2019-01-05    0
cs95
  • 379,657
  • 97
  • 704
  • 746
  • Good idea. I suppose I'm making more complicated than it needs to be! Now I just need a way to initialize the values of that Series to zero. Thanks for your answer. – JasonArg123 Dec 12 '18 at 18:49
  • 1
    @JasonArg123 Stop wondering, because I've done it for you (see edit). – cs95 Dec 12 '18 at 18:53