计算标准差时忽略多个NaN

2024-09-30 08:22:55 发布

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

我有下面的熊猫数据帧,其中包含一些5分钟的日内数据。DeltaBetweenClose是开市当天(美国东部时间9:30)的第一个交易栏。你知道吗

    time     Date       symbol    DeltaBetweenClose 
    9:35    2017-07-17  spy        NaN 
    9:40    2017-07-17  spy       -1.2                     
    ..........................................
    ..........................................    
    16:00   2018-07-17  spy        1.7
    9:35    2017-07-18  spy        NaN
    9:40    2017-07-18  spy        0.3                      
    ..........................................
    ..........................................        
    9:35    2018-07-17  nflx       NaN

我正在尝试创建一个列CloseDelta_sd,该列计算按symbol分组的DeltaBetweenClose列的滚动标准偏差,该列查看前面的30个条并计算标准偏差,同时忽略NaNs。下面的尝试返回所有NaNs。当DeltaBetweenClose列的顶部只有一个NaN时,该操作有效。你知道吗

df['CloseDelta_sd'] = df.groupby('symbol').DeltaBetweenClose.transform(lambda x: x.rolling(30).std())

Tags: 数据dfdatetime时间交易sdnan
1条回答
网友
1楼 · 发布于 2024-09-30 08:22:55

问题不在于std,因为默认情况下它跳过NaN,而在于rolling。你知道吗

您需要使用^{}参数:

Minimum number of observations in window required to have a value (otherwise result is NA). For a window that is specified by an offset, this will default to 1.

由于您提供了int而不是偏移量,因此最终会有许多NaN组,解决方法很简单:

(df.groupby('symbol').DeltaBetweenClose
    .transform(lambda x: x.rolling(30, min_periods=1).std()))

相关问题 更多 >

    热门问题