Reputation: 7394
Im using pandas datareader to get stock data.
import pandas as pd
import pandas_datareader.data as web
ABB = web.DataReader(name='ABB.ST',
data_source='yahoo',
start='2000-1-1')
However by default freq is not set on the resulting dataframe. I need freq to be able to navigate using the index like this:
for index, row in ABB.iterrows():
ABB.loc[[index + 1]]
If freq is not set on DatetimeIndex im not able to use +1
etc to navigate.
What I have found are two functions astype
and resample
. Since I already know to freq resample
looks like overkill, I just want to set freq to daily.
Now my question is how can i use astype on ABB to set freq to daily?
Upvotes: 36
Views: 68364
Reputation: 33
Use .asfreq on the whole dataframe but it doesn't have an inplace argument so you need to save it an object.
ABB = ABB.asfreq("D")
Upvotes: 0
Reputation: 878
ABB is pandas DataFrame, whose index type is DatetimeIndex.
DatetimeIndex has freq attribute which can be set as below
ABB.index.freq = 'd'
Check out the change
ABB.index
Upvotes: 18
Reputation: 13284
Try:
ABB = ABB.asfreq('d')
This should change the frequency to daily with NaN
for days without data.
Also, you should rewrite your for-loop
as follows:
for index, row in ABB.iterrows():
print(ABB.loc[[index + pd.Timedelta(days = 1)]])
Thanks!
Upvotes: 44
Reputation: 863501
If need change frequency of index resample
is for you, but then need aggregate columns by some functions like mean
or sum
:
print (ABB.resample('d').mean())
print (ABB.resample('d').sum())
If need select another row use iloc
with get_loc
for find position of value in DatetimeIndex
:
print (ABB.iloc[ABB.index.get_loc('2001-05-09') + 1])
Open 188.00
High 192.00
Low 187.00
Close 191.00
Volume 764200.00
Adj Close 184.31
Name: 2001-05-10 00:00:00, dtype: float64
Upvotes: 4