【问题标题】:.loc to filter database by date.loc 按日期过滤数据库
【发布时间】:2021-03-29 00:52:31
【问题描述】:

我在过去几周学习了 python,但我遇到了 .loc 函数的问题。

我有一个由每日股票价格和日期组成的数据框 (BAC) 作为索引(这似乎是一个日期时间对象)。我只想过滤 2008 年的日期并对“关闭”列进行滚动平均(30 天)。

这是我的代码和输出:

BAC.info

OUT : <class 'pandas.core.frame.DataFrame'> DatetimeIndex: 2769 entries, 2015-12-31 to 2005-01-03 Data columns (total 5 columns):
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 2769 entries, 2015-12-31 to 2005-01-03
Data columns (total 5 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   Open    2769 non-null   float64
 1   High    2769 non-null   float64
 2   Low     2769 non-null   float64
 3   Close   2769 non-null   float64
 4   Volume  2768 non-null   float64
dtypes: float64(5)
memory usage: 209.8 KB

和:

BAC['Close'].loc['2008-01-01':'2009-01-01'].rolling(window=30).mean()

OUT: Series([], Name: Close, dtype: float64)

代码:BAC.loc['2008-01-01':'2009-01-01', 'Close'].rolling(window=30).mean() 产生相同的结果。

所以,我没有弄错,但我认为格式存在问题。我所关注的课程使用 .ix,它现在已被弃用,我知道 .loc 或多或少可以做同样的事情(如果按列或行号过滤,则使用 .iloc)。

在那之后,我尝试了:

BAC.loc['2008', 'Close' ].rolling(window=30).mean()

OUT : 
2008-12-31          NaN
2008-12-30          NaN
2008-12-29          NaN
2008-12-26          NaN
2008-12-24          NaN
                ...    
2008-01-08    35.948233
2008-01-07    35.858433
2008-01-04    35.775933
2008-01-03    35.705700
2008-01-02    35.656400
Name: Close, Length: 253, dtype: float64

所以它起作用了,但是在 2008 年末而不是开始时开始滚动窗口......为什么会这样?

任何帮助将不胜感激。谢谢!

【问题讨论】:

    标签: python date rolling-computation .loc


    【解决方案1】:

    BAC.info 的输出显示您的索引已反转。尝试做一个BAC.sort_index(inplace=True)

    除此之外,我在您的代码中看不到任何错误。这是我得到的:

    >>> import pandas as pd
    >>> import numpy as np
    >>> BAC = pd.date_range(start='2008-01-01', end='2009-12-31').to_frame()
    >>> BAC['Close'] = np.random.randint(0, 70, BAC.shape[0])
    
    >>> BAC['Close'].loc['2008-01-01':'2009-01-01'].rolling(window=30).mean()
    2008-01-01          NaN
    2008-01-02          NaN
    2008-01-03          NaN
    2008-01-04          NaN
    2008-01-05          NaN
                    ...    
    2008-12-28    39.566667
    2008-12-29    40.633333
    2008-12-30    39.533333
    2008-12-31    39.266667
    2009-01-01    39.866667
    Freq: D, Name: Close, Length: 367, dtype: float64
    >>> BAC.loc['2008', 'Close'].rolling(window=30).mean()
    2008-01-01          NaN
    2008-01-02          NaN
    2008-01-03          NaN
    2008-01-04          NaN
    2008-01-05          NaN
                    ...    
    2008-12-27    38.833333
    2008-12-28    39.566667
    2008-12-29    40.633333
    2008-12-30    39.533333
    2008-12-31    39.266667
    Freq: D, Name: Close, Length: 366, dtype: float64
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-16
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多