Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change week start date using df.resample?

I'm using Python 3.6 and this is my code:

trainFile = r'C:\download\combine\Combine_1.csv'
pwd = os.getcwd()
os.chdir(os.path.dirname(trainFile))
df = pd.read_csv(os.path.basename(trainFile))
os.chdir(pwd)

df['date'] = pd.to_datetime(df['date'])
df = df.set_index('date')
week = df.resample('w').mean()

week.to_csv('week_combine.csv')

I try to make daily data into weekly data, but now the week starts at every Sunday, how can I change it into every Monday?

For example, now the results look like:

...
2017-09-10
2017-09-17
2017-09-24
...

but I want to change it into:

...
2017-09-11
2017-09-18
2017-09-25
...

Any idea?

like image 674
Jenny Avatar asked Mar 08 '23 12:03

Jenny


1 Answers

Need W-MON anchored offset:

rng = pd.date_range('2017-09-09', periods=15)
df = pd.DataFrame({'a': range(15)}, index=rng)  


week = df.resample('W-MON').mean()
print (week)
             a
2017-09-11   1
2017-09-18   6
2017-09-25  12
like image 154
jezrael Avatar answered Mar 16 '23 08:03

jezrael