创建 DataFrame 后设置 Pandas DatetimeIndex 的频率

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41535322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:44:55  来源:igfitidea点击:

Setting freq of pandas DatetimeIndex after DataFrame creation

pythonpandas

提问by user3139545

Im using pandas datareader to get stock data.

我使用Pandas数据阅读器来获取股票数据。

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:

但是,默认情况下,不会在结果数据帧上设置 freq。我需要 freq 才能使用这样的索引进行导航:

for index, row in ABB.iterrows():
    ABB.loc[[index + 1]]

If freq is not set on DatetimeIndex im not able to use +1etc to navigate.

如果未在 DatetimeIndex 上设置 freq,我将无法使用+1等进行导航。

What I have found are two functions astypeand resample. Since I already know to freq resamplelooks like overkill, I just want to set freq to daily.

我发现的是两个函数astyperesample. 由于我已经知道 freqresample看起来有点矫枉过正,我只想将 freq 设置为每天。

Now my question is how can i use astype on ABB to set freq to daily?

现在我的问题是如何在 ABB 上使用 astype 将频率设置为每天?

采纳答案by Abdou

Try:

尝试:

ABB = ABB.asfreq('d')

This should change the frequency to daily with NaNfor days without data.

这应该在NaN没有数据的情况下将频率更改为每天。

Also, you should rewrite your for-loopas follows:

此外,你应该重写你for-loop的如下:

for index, row in ABB.iterrows():
    print(ABB.loc[[index + pd.Timedelta(days = 1)]])

Thanks!

谢谢!

回答by Rohit Nandi

ABB is pandas DataFrame, whose indextype is DatetimeIndex.

ABB 是 pandas DataFrame,其索引类型为DatetimeIndex

DatetimeIndexhas freqattribute which can be set as below

DatetimeIndex具有freq属性,可以设置如下

ABB.index.freq = 'd'

Check out the change

看看变化

ABB.index

回答by jezrael

If need change frequency of index resampleis for you, but then need aggregate columns by some functions like meanor sum:

如果需要更改索引的频率resample适合您,但需要通过某些函数(如mean或)聚合列sum

print (ABB.resample('d').mean())
print (ABB.resample('d').sum())

If need select another row use ilocwith get_locfor find position of value in DatetimeIndex:

如果需要选择其他行使用ilocget_loc用于在价值发现的位置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