首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python -使用dataframe的顺序循环

Python -使用dataframe的顺序循环
EN

Stack Overflow用户
提问于 2018-07-19 02:16:25
回答 2查看 764关注 0票数 2

我正在尝试使用其他不同数据帧提供的一些参数在数据帧的行上计算递归方程。下面提供了该方程,并应对矩阵的每一列执行该方程。它看起来像一个指数移动平均值,除了衰减不是恒定的,并且是从另一个数据帧给出的。

给定:

  • 与输出

相同大小的矩阵α

  • 与输出

相同大小的矩阵P

  • 与输出

相同宽度的向量M0

我用一个双循环(用.iloc)做了第一次尝试:

代码语言:javascript
复制
import pandas as pd
import numpy as np

"""
Assuming inputs:
    - Matrix P of size 1000x4
    - Matrix alpha of size 1000x4
    - Vector M0 of size 1X4
"""

# input variables
height = 1000
width = 4
np.random.seed(1)
P = pd.DataFrame(np.random.normal(loc=170, scale=12, size=(height, width)), index=range(height), columns=range(width))
np.random.seed(1)
alpha = pd.DataFrame(np.random.normal(loc=0.04, scale=0.04, size=(height, width)), index=range(height), columns=range(width))
np.random.seed(1)
M0 = pd.DataFrame(np.random.normal(loc=170, scale=12, size=(height, width)), columns=range(width))


# Output table
MA = P.copy()*0
MA.iloc[0] = M0 

# Recursive equation
for x in range(width):
    for y in range(1, height):
        MA.iloc[y][x] = alpha.iloc[y][x]*P.iloc[y][x] + (1-alpha.iloc)* MA.iloc[y-1][x]

通过将probleme扩展为累积prod (参见下面的等式),使用矢量化进行第二次尝试,但检索不到预期的值(代码将在稍后更新):

我可以重写我的数学。然而,我想知道是否有更有效/更简单的方法来做这件事,因为这需要一段时间。

谢谢你的帮助!

更新1:几条评论:

  • 我的原始数据框是不同资产(列)的价格矩阵,行是天数从上到下(过去在顶部,现在在底部)
  • 从那里开始,我的初始移动平均日取决于返回初始窗口的资产的函数。因此,算法不是列对称的-My策略是循环遍历列,提取所需的向量,执行数值计算并将其放回数据帧中:

递归方式:我将代码重写为:

代码语言:javascript
复制
ema = P.copy()*0

for x in ema.columns:

    # define which row to start the algorithm
    start = max (100, 250, int(windows[x]))

    # store index (dates) to be re-inject after numpy calculus
    i_d = (p.iloc[start:]).index

    # extract corresponding vectors from original matrices
    alpha_temp= alpha.iloc[start:][x].values
    p_temp = p.iloc[start:][x].values
    ema_temp = ema.iloc[start:][x].values

    #MO 
    ema_temp[0] = m0[x]

    #recursive equation
    for y in range (1, len(ema_temp)):
        ema_temp[y] = alpha_temp[y]*p_temp[y]+(1-alpha_temp[y])*ema_temp[y-1]

    #transformation into a dtaframe and re-injection in the datframe ema
    ema_temp = pd.DataFrame(ema_temp)
    ema_temp.index=ema.index[-len(ema_temp):]
    ema_temp.columns=[x]
    ema.update(ema_temp)

方程的展开

谢谢你的帮助,a_guest。

代码语言:javascript
复制
# This is the product within the summation.
prod = np.flipud(np.cumprod(1 - np.flipud(alpha)))

# This is the sum over the scaled products.
sum_prod = np.cumsum((alpha * P)[:-1] * prod[1:])

# Combining all elements.
result = (alpha * P)[1:] + sum_prod + M0*prod[0]

我试过你的代码,但我不能提供正确的答案。我不能保证100%地理解它。

假设我的数据是向下的,第一行将提供:

我不明白如何在第二行中使用它,因为它已经到处都包含了1-a_n。

非常感谢!

EN

回答 2

Stack Overflow用户

发布于 2018-07-19 08:47:13

我会建议两个修改:

1.用于简化:由于用于计算移动平均的列的独立性。一个for循环就足以遍历各行。此外,这将提供一个小的性能提升。

代码语言:javascript
复制
for y in range(1,height):
    MA.iloc[y] = alpha.iloc[y]*P.iloc[y] + (1-alpha.iloc[y])*MA.iloc[y-1]

2.用于计算效率/速度的:将索引与numpy ndarray/数组一起使用,而不是pandas dataFrame/系列,将在性能上提供相当大的改进。

代码语言:javascript
复制
MA = MA.values                               # converted to ndarray from dataFrame
alpha = alpha.values                         # -do-
P = P.values                                 # -do-

for y in range(1,height):
    MA[y] = alpha[y]*P[y] + (1-alpha[y])*MA[y-1]
票数 1
EN

Stack Overflow用户

发布于 2018-07-19 05:24:25

您对递归公式的展开就是正确的方式,您可以使用numpy工具来计算各种元素。由于每列的结果是独立的计算,因此可以为单个(1D)列建立该算法。通过添加相应的维度并为每个操作适当地指定axis关键字,可以轻松扩展多个(2D)列。因此,对于1D情况,它是:

代码语言:javascript
复制
# This is the product within the summation.
prod = np.flipud(np.cumprod(1 - np.flipud(alpha)))

# This is the sum over the scaled products.
sum_prod = np.cumsum((alpha * P)[:-1] * prod[1:])

# Combining all elements.
result = (alpha * P)[1:] + sum_prod + M0*prod[0]

请注意,结果是针对n > 1 (使用您的表示法;在Python的表示法中为n > 0 )给出的,但是n = 1 (n = 0)的剩余值可以直接计算,因为和是零。

编辑

通过将用于计算的维度提供给运算的axes关键字,可以实现对2D的扩展:

代码语言:javascript
复制
prod = np.flip(np.cumprod(1 - np.flip(alpha, axis=0), axis=0), axis=0)
sum_prod = np.cumsum((alpha * P)[:-1] * prod[1:], axis=0)
result = (alpha * P)[1:] + sum_prod + M0*prod[0]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51408552

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档