Numpy函数/方法用于计算移动范围?

huangapple go评论52阅读模式
英文:

Numpy function/method to calculate moving range?

问题

以下是翻译好的代码部分:

要在numpy中计算移动范围
编写了一个使用Pandas的函数希望以简单/快速的方式返回具有等效值的numpy数组不需要新数组的名称只需要值

def get_moving_range(my_series, na_replace_value=None):
    """返回计算的移动范围系列对象。

    Args:
        my_series (pandas series): 从中导出移动范围的系列。
        na_replace_value (numeric, optional): 默认情况下,移动范围的第一个值为nan,如果需要不同的值,请使用此参数,否则保留为None。默认为None。
    """
    # 重命名系列以使其更容易处理
    my_series.name = 'original'
    # 转换为DataFrame
    df = my_series.to_frame()
    # 创建偏移量以便轻松进行Xn - Xn-1计算
    df['shifted'] = df['original'].shift(1)
    # 计算移动范围值
    df['Moving Range'] = abs(df['original'] - df['shifted'])
    if na_replace_value != None:
        df.fillna(value=na_replace_value, inplace=True) 
    return df['Moving Range']
英文:

Want to calculate moving range in numpy.

Wrote function using Pandas, want simple/fast way to return numpy array with equivalent values. Don't need the name of new array, just the values.

def get_moving_range(my_series, na_replace_value=None):
        """Returns calculated moving range series object.

        Args:
            my_series (pandas series): Series to derive moving range from.
            na_replace_value (numeric, optional): first value of moving range is nan by default, if different value is desired use this, otherwise leave as None. Defaults to None.
        """
        # rename series to keep it easy
        my_series.name = 'original'
        # convert to DataFrame
        df = my_series.to_frame()
        # create the offset so I can do the Xn - Xn-1 calculation easy
        df['shifted'] = df['original'].shift(1)
        # calculate the moving range values
        df['Moving Range'] = abs(df['original'] - df['shifted'])
        if na_replace_value != None:
                df.fillna(value=na_replace_value, inplace=True) 
        return(df['Moving Range'])

答案1

得分: 0

def np_moving_range(array, fill_val=None):
    return np.r_[fill_val, np.diff(array)]
英文:

just use

def np_moving_range(array, fill_val = None):
   return np.r_[fill_val, np.diff(array)]

huangapple
  • 本文由 发表于 2023年3月1日 09:23:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75598797.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定