英文:
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)]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论