Setting freq of pandas DatetimeIndex after DataFrame creation
32,669
Solution 1
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!
Solution 2
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
Related videos on Youtube
Author by
user3139545
Updated on July 09, 2022Comments
-
user3139545 almost 2 years
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
andresample
. Since I already know to freqresample
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?
-
Abdou over 7 years
ABB = ABB.asfreq('d')
should change the frequency to daily withNaN
for days without data. Also, changeABB.loc[[index + 1]]
toABB.loc[[index + pd.Timedelta(days = 1)]]
inside thatfor-loop
.
-
-
Rich Andrews about 2 yearsThe resample is essential if there is no way to pre-validate the regularity of the index - big data sets from external systems always have error and blindly setting the index frequency is likely not safe. While OP knows the frequency ahead of time, this answer is more literal.