简体   繁体   中英

How to accept data starting from most recent monday only

I have the following code:

import pandas as pd
from pandas import datetime
from pandas import DataFrame as df
import matplotlib
from pandas_datareader import data as web
import matplotlib.pyplot as plt
import datetime
import numpy as np

stock = '^GSPC'
start = datetime.date(2000,1,1)
end = datetime.date.today()
data = web.DataReader(stock, 'yahoo',start, end)
data.index = pd.to_datetime(data.index, format ='%Y-%m-%d')
data['Day Name'] = data.index.weekday_name
data.set_index('day',append=True,inplace=True)
data.set_index('Day Name', append=True, inplace=True)
data['pct_day']= data['Adj Close'].pct_change()
df = data.groupby(['Day Name']).mean()
df = df.drop( index=['Saturday','Sunday'])
df = df.reindex(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'])

What i need to do here is, regardless of the date entered, the data should only be accepted from the most recent Monday and nothing before that. Any help here would be appreciated, thanks in advance.

You can remove values before first Monday with Series.eq , Series.cumsum and get all rows with not equal 0 by Series.ne :

data['Day Name'] = data.index.weekday_name

data = data[data['Day Name'].eq('Monday').cumsum().ne(0)].copy()

data.set_index('day',append=True,inplace=True)

Another idea is use Series.idxmax for first index value and pass to DataFrame.loc , only necessary at least one Monday in data:

data['Day Name'] = data.index.weekday_name

data = data.loc[data['Day Name'].eq('Monday').idxmax():]

data.set_index('day',append=True,inplace=True)

Sample :

rng = pd.date_range('2017-04-01', periods=10)
data = pd.DataFrame({'a': range(10)}, index=rng)  

data['Day Name'] = data.index.weekday_name
data = data[data['Day Name'].eq('Monday').cumsum().ne(0)].copy()
print (data)
            a   Day Name
2017-04-03  2     Monday
2017-04-04  3    Tuesday
2017-04-05  4  Wednesday
2017-04-06  5   Thursday
2017-04-07  6     Friday
2017-04-08  7   Saturday
2017-04-09  8     Sunday
2017-04-10  9     Monday

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM