重新理解pandas.DataFrame.ewm
Overview
《理解pandas.DataFrame.ewm》
《理解exponential weighted || 指数》
通过上述两文初步了解了ewm,但还是没能很清楚,几经周折。
Source code
@doc(ExponentialMovingWindow) def ewm(self,com=None,span=None,halflife=None,alpha=None,min_period=0,adjust=True,ignore_na=False,axis=0,times=None, ):axis = self._get_axis_number(axis)return ExponentialMovingWindow(self,com=com,span=span,halflife=halflife,alpha=alpha,min_period=min_periods,adjust=adjust,ignore_na=ignore_na,axis=axis,times=times,)
class ExponentialMovingWindow(_Rolling): # inherite from class _Rolling_attrubutes = ["com", "min_periods", "adjust", "ignore_na", "axis"]def __init__(self,obj,com: Optional[float] = None,span: Optional[float] = None,halflife: Optional[Union[float, TimedeltaConvertibleTypes]] = None,alpha: Optional[float] = None,min_periods: int = 0,adjust: bool = True,ignore_na: bool = False,axis: int = 0,times: Optional[Union[str, np.array, FrameOrSeries]] = None,):self.com: Optional[float]self.obj = objself.min_periods = max(int(min_periods), 1)self.adjust = adjustself.ignore_na = ignore_naself.axis = axisself.on = Noneif times is not None:if isinstance(time, str):times = self._selected_obj[times] if not is_datetime64_ns_dtype(times):raise ValueError("times must be datetime64[ns] dtype.")if len(times) != len(obj):raise ValueError("times must be the same length as the object")if not isinstance(halflife, (str, datetime.timedelta)):raise ValueError("halflife must be a string or datetime.timedelta object")self.times = np.asarray(times.astype(np.int64))self.halflife = Timedelta(halflife).valueif common.count_not_none(com, span, alpha)>0:self.com = get_center_of_mass(com, span, None, alpha) # 三选一,通过com span alpha确定质心else:self.com = Noneelse:if halflife is not None and isinstance(halflife, (str, datetime.timedelta)):raise ValueError("halflife can only be a timedelta convertible argument if times is not None")self.times = Noneself.halflife = Noneself.com = get_center_of_mass(com, span, halflife, alpha)def _apply(self, func):np.apply_along_axis(func, self.axis, values)@Substitution(name="ewm", func)_name="mean"@Appender(_doc_template)def mean(self, *args, **kwargs):nv.validate_window_func("mean", args, kwargs)window_func = partial()return self._apply(window_func)@Substitution(name="ewm", func)_name="cov"@Appender(_doc_template)def cov(self, other, pairwise, bias, **kwargs):pairwise=True if pairwise is None else pairwise
pandas.DataFrame.ewm() 返回一个Exponential Moving Windows类
pandas.DataFrame.ewm().mean() 通过Exponential Moving Windows类调用自身的mean()方法实现结果。
Point 1 : adjust = True or False
The ew functions support two variants of exponential weights.
The default
adjsut = True
, uses the weights wi=(1−α)iw_i=(1-\alpha)^iwi=(1−α)i which gives EW moving average:
yt=xt+(1−α)xt−1+(1−α)tx01+(1+α)+(1+α)ty_t=\frac{x_t+(1-\alpha)x_{t-1}+(1-\alpha)^tx_{0}}{1+(1+\alpha)+(1+\alpha)^t} yt=1+(1+α)+(1+α)txt+(1−α)xt−1+(1−α)tx0
Whenadjust = False
is specified, moving average are calculated as
y0=x0yt=(1−α)yt−1+αxty_0=x_0\\y_t=(1-\alpha)y_{t-1}+\alpha x_t y0=x0yt=(1−α)yt−1+αxt
The difference between the above two variants because we are dealing with series which have finite history.Point 2 : alpha vs. com,span,halflife
α={11+cforcom21+sforspan1−explog0.5hforhalflife\alpha = \begin{cases} \frac{1}{1+c}\;\;\;for \;com\\\frac{2}{1+s}\;\;\; for\;span \\ 1-exp^{\frac{log0.5}{h}}\;\;\;for\;halflife\end{cases} α=⎩⎪⎨⎪⎧1+c1forcom1+s2forspan1−exphlog0.5forhalflife
span corresponds to what is commonly called an “N-day EW moving average”
Center of mass has a more physical interpretation and can be thought of in terms of span : c=s−12c=\frac{s-1}{2}c=2s−1
Half-life is the period of time for the exponential weighted to reduce to one half.
Alpha specifies the smoothing factor directly.
Point 3 : min_periods
Has the same meaning it does for all the
.expanding
and.rolling
methods : no output values will be set until at leastmin_periods
non-null values are encountered in the window.一个window周期内,至少又min_periods个数据才进行计算,不然就返回Na.
Point4 : ignore_na
ignore_na = True weights are calculated by ignoring intermediate null values.
Reference
- 3.5 Exponentially Weighted Windows
重新理解pandas.DataFrame.ewm相关推荐
- DataFrame指数权重窗口ewm使用: DataFrame.ewm([com, span, halflife, …])
@创建于:20210311 @修改于:20210311 文章目录 1.背景 2.ewm介绍 2.1 DataFrame ewm API接口介绍 2.2 参数介绍 3.例子 3.1 必选参数比较 3.2 ...
- pandas dataframe缺失值(np.nan)处理:识别缺失情况、删除、0值填补、均值填补、中位数填补、加缺失标签、插值填充详解及实例
pandas dataframe缺失值(np.nan)处理:识别缺失情况.删除.0值填补.均值填补.中位数填补.加缺失标签.插值填充详解及实例 isnull().natna().isna().fill ...
- pandas dataframe column_Python数据分析——Pandas 教程(下)
Python数据分析--Pandas 教程(上) 上节,我们讲了 Pandas 基本的数据加载与检索,这节我们讲讲如何进行数据比较. Pandas系列对象 在 Pandas 中我们获取指定列的数据有多 ...
- python mulit函数_python – 将函数应用于MultiIndex pandas.DataFrame列
我有一个MultiIndex pandas DataFrame,我想在其中的一个列中应用一个函数,并将结果分配给同一列. In [1]: import numpy as np import panda ...
- pandas.DataFrame.iloc的使用
pandas.DataFrame.iloc的使用 今天学习时遇到了这个方法,为了加深理解做一下笔记. 这是该方法的文档,从中可以看出,中括号里允许输入可情形有5种. 此外,iloc方法既可以索引行数据 ...
- pandas.DataFrame()的基本操作
感觉上pandas的DataFrame就像numpy中的矩阵,不过它拥有列名和索引名,实际操作起来会更方便一些. 如: df = pd.read_clipboard() df.columns df.R ...
- python怎么画参数函数图像_详解pandas.DataFrame.plot() 画图函数
首先看官网的DataFrame.plot( )函数 DataFrame.plot(x=None, y=None, kind='line', ax=None, subplots=False, share ...
- pandas dataframe创建_Python数据分析基础之Pandas学习 (上)
全文共 20592 字,63 幅图,预计阅读时间 52 分钟.[注:本帖小节 2.2 用万矿里的 WindPy 来下载金融数据]0引言 本文是 Python 系列的第六篇 Python 入门篇 (上) ...
- [转载] 使用Python在Pandas Dataframe中建立索引
参考链接: 用Pandas建立索引并选择数据 In Numpy arrays, we are familiar with the concepts of indexing, slicing, and ...
最新文章
- 第十六届全国大学智能车竞赛创意组比赛国赛获奖名单
- xshell搭建宝塔没有远程命令密码框框弹出来_服务器安装宝塔控制面板+wordpress搭建个人网站...
- mysql可以登陆sqlyog1862_MySQL错误号码1862:your password has expired
- ext2删除文件恢复笔记
- 爬虫之requests库的使用
- 5. http://kb.cnblogs.com/page/90838/
- 网络编程技术(技术总结)
- 投屏软件_duet for Mac(Mac投屏软件)
- [算法]px4位置估计-inav (2017/10/26更新)
- 交叉编译 WPA_Supplicant
- 天狼星网络验证源码/官方正版/内附搭建教程
- CRAFT(Character Region Awareness for Text Detection)
- 八大地图API开发平台大比拼
- python中sub的用法_Python Pandas Series.sub()用法及代码示例
- python 今日头条 控制手机_Python脚本下载今日头条视频(附加Android版本辅助下载器)...
- 奈奎斯特定理与香农定理
- java sapi.spvoice_SAPI使用总结——SpVoice的使用方法
- vst开启语音服务器,VST语音遥控器体验记
- 电脑开不了机提示checking media的解决方法
- 王峻涛访谈录(四)电子商务是什么?