【问题标题】:Setting freq of pandas DatetimeIndex after DataFrame creation创建 DataFrame 后设置 pandas DatetimeIndex 的频率
【发布时间】:2021-12-26 02:55:05
【问题描述】:

我正在使用 pandas 数据阅读器来获取股票数据。

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

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

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

如果没有在 DatetimeIndex 上设置频率,我将无法使用+1 等进行导航。

我发现了两个函数astyperesample。由于我已经知道频率 resample 看起来有点矫枉过正,我只想将频率设置为每天。

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

【问题讨论】:

  • ABB = ABB.asfreq('d') 应该在没有数据的日子里用NaN 将频率更改为每天。另外,将for-loop 中的ABB.loc[[index + 1]] 更改为ABB.loc[[index + pd.Timedelta(days = 1)]]
  • 你应该把它作为答案

标签: python pandas


【解决方案1】:

如果需要索引resample 的更改频率适合您,但需要通过meansum 等函数聚合列:

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

如果需要选择另一行,请使用ilocget_locDatetimeIndex 中查找值的位置:

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

【讨论】:

    【解决方案2】:

    试试:

    ABB = ABB.asfreq('d')
    

    对于没有数据的日子,这应该将频率更改为NaN 的每日频率。

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

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

    谢谢!

    【讨论】:

      【解决方案3】:

      ABB为pandas DataFrame,其index类型为DatetimeIndex

      DatetimeIndexfreq 属性,可以如下设置

      ABB.index.freq = 'd'
      

      查看更改

      ABB.index
      

      【讨论】:

        猜你喜欢
        • 2019-10-08
        • 1970-01-01
        • 1970-01-01
        • 2019-07-23
        • 2019-11-04
        • 2014-12-16
        • 2015-11-17
        • 1970-01-01
        相关资源
        最近更新 更多