创建数据帧后设置pandas DatetimeIndex的频率

2024-06-11 14:24:24 发布

您现在位置:Python中文网/ 问答频道 /正文

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

import pandas as pd
import pandas_datareader.data as web
ABB = web.DataReader(name='ABB.ST', 
                     data_source='yahoo',
                     start='2000-1-1')

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

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

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

我发现了两个函数astyperesample。因为我已经知道freqresample看起来有点过头了,所以我只想将freq设置为daily。

现在我的问题是如何使用ABB上的astype将freq设置为daily?


Tags: 数据importwebpandasdataindexasdaily
2条回答

如果需要更改索引^{}的频率适合您,但是需要通过一些函数(如meansum)来聚合列:

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

如果需要选择另一行,请使用^{}^{}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

尝试:

ABB = ABB.asfreq('d')

这应该会在没有数据的情况下将频率更改为daily withNaN

另外,您应该重写for-loop如下:

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

谢谢!

相关问题 更多 >