V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
wuwukai007
V2EX  ›  Python

记一个 pandas rolling corr 窗口大小不固定 计算问题。

  •  
  •   wuwukai007 · 2020-03-20 00:59:58 +08:00 · 2160 次点击
    这是一个创建于 1470 天前的主题,其中的信息可能已经有所发展或是发生改变。
    # pandas rolling.corr 可以按窗口周期计算 相似性(斜方差)
    # 但是 rolling(window= )窗口只能是 d(天) s(秒) 或 固定 int
    # 如果窗口 是年(A),或者月(M),或者季度(Q),就不行了,
    # 可以将所有月或年 内的日期填平,值补 NAN,这样计算结果一样的,之后在删掉补齐的日期。
    # 或者有没有更好的方法,被这个折磨了
    
    
    df = pd.DataFrame(np.random.randn(1000, 4),
                                index=pd.date_range('1/1/2000',freq='7D',periods=1000),
                                columns=['A', 'B', 'C', 'D'])
    df.head()
    '''   
    	            A	          B	          C                 D
    2000-01-01	-0.747009	0.404950	-0.154117	0.585156
    2000-01-08	-0.895967	-0.325115	-0.272460	-0.919274
    2000-01-15	-1.288576	0.662856	0.914934	-1.135986
    2000-01-22	0.160453	-0.660789	0.912832	-1.244605
    2000-01-29	1.936950	-0.510921	-1.882941	1.788139
    '''
    d = pd.date_range(start='2000-01-01',end='2019-02-23')
    date = pd.DataFrame(np.zeros(len(d)),index=d)
    df3 = date.join(df)[df.columns]
    df3.head()
    
    '''
    	A	B	C	D
    2000-01-01	-0.747009	0.40495	-0.154117	0.585156
    2000-01-02	NaN	NaN	NaN	NaN
    2000-01-03	NaN	NaN	NaN	NaN
    2000-01-04	NaN	NaN	NaN	NaN
    2000-01-05	NaN	NaN	NaN	NaN
    '''
    
    A = df3['2014-09-26':'2015-09-26']
    A['A'].corr(A['B'])  # 0.3241573893873542
    
    B = df['2014-09-26':'2015-09-26']
    B['A'].corr(B['B']) # 0.3241573893873542
    
    res = df3['A'].rolling('366d').corr(df3['B'])
    res['2015-09-26'] #0.3241573893873542
    result = res[df.index]
    
    
    2 条回复    2020-03-20 09:25:34 +08:00
    billgreen1
        1
    billgreen1  
       2020-03-20 08:55:55 +08:00
    rolling 需要一个固定的长度,所以 1M 这样的,有时候 30 天,有时候 31 天,是不行的。

    你上面的例子,可以使用 resample

    ~~~python
    df.resample('1D').asfreq().rolling('366d').corr(...)
    ~~~
    wuwukai007
        2
    wuwukai007  
    OP
       2020-03-20 09:25:34 +08:00
    @billgreen1 可以,asfreq 自动填充日期,比手工的优雅多了,感谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2772 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 12:51 · PVG 20:51 · LAX 05:51 · JFK 08:51
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.