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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.