Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting freq of pandas DatetimeIndex after DataFrame creation

Tags:

python

pandas

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?

like image 548
user3139545 Avatar asked Jan 08 '17 17:01

user3139545


People also ask

How do you change frequency in pandas?

To create a PeriodIndex, use the pandas. PeriodIndex() method. To set the frequency, use the freq parameter.

How can I get DatetimeIndex in pandas?

date attribute outputs an Index object containing the date values present in each of the entries of the DatetimeIndex object. Example #1: Use DatetimeIndex. date attribute to find the date part of the DatetimeIndex object.

How do I change the index of a data frame?

To reset the index in pandas, you simply need to chain the function . reset_index() with the dataframe object. On applying the . reset_index() function, the index gets shifted to the dataframe as a separate column.

What is DatetimeIndex pandas?

class pandas. DatetimeIndex [source] Immutable ndarray of datetime64 data, represented internally as int64, and which can be boxed to Timestamp objects that are subclasses of datetime and carry metadata such as frequency information.


2 Answers

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!

like image 139
Abdou Avatar answered Sep 27 '22 20:09

Abdou


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
like image 23
Rohit Nandi Avatar answered Sep 27 '22 19:09

Rohit Nandi