Python和Pandas - 列 "计数方向" 和显示 "至今平均值"

2024-10-05 10:47:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧,包含在特定分钟结束时的(股票)价格。在

DF列是:

  • 分钟编号:0-1440,0代表午夜,480代表上午8:00(60*8)
  • 在价格:股票价格最后一分钟
  • 变化:价格从上一次的变化。分钟
  • 方向:改变的方向
import numpy.random as nprnd
from pandas import DataFrame

n = 10    # Number of samples
# Starting at 8:00 AM, set some (n) random prices between 4-5
df = DataFrame({'minute_id': range(480,480+n), 'price':(5-4) * nprnd.random(n) + 4 })
df['change'] = df.price - df.price.shift(1)
df['direction'] = df.change.map(lambda x: 0 if x == 0 else x/abs(x))
df = df.dropna()
df

我想给这个数据框加几列。在

  1. 目前均价 对于第一排,它会有价格。 对于第二排,它将有两个第一排的平均价格 对于第n行,它将具有前n行的平均价格
  2. 当前方向上“更改”列的总和 (每次“方向”切换时将归零)
  3. 按当前方向计算,直到现在 对于每一行,该行在当前方向上的编号是多少。在
  4. 最后4行均价

我可以通过一次迭代DF行来创建所有这些列。 但我确信还有一种更为(Python式的)方式来做这件事。在

我也不知道如何处理丢失的数据(如果我在分钟内有差距)


编辑:

在我想添加的4列中,1和4很容易。。。在

C4:这只是一个周期为4的滚动平均数

C1:滚动平均可以得到另一个最小周期的参数。在

将其设置为1并将窗口大小设置为df的长度,将为集合中的每一行提供一个运行平均值。在

df['rolling_avg'] = pd.rolling_mean(df.price, n, 1)

对于其他两个专栏,我仍在努力找到最好的方法。在


Tags: 数据importdataframedf代表价格random方向
1条回答
网友
1楼 · 发布于 2024-10-05 10:47:43

好吧,经过一番“闲逛”之后,我有了一个对我有用的东西。在

这也许可以用一种更“泛泛而谈”的方式来完成,但这是一种合理的方式来完成它。在

我要感谢安迪·海登、杰夫和菲利普·克劳德,感谢他们指出“给熊猫10分钟” 它没有包含直接的答案,但很有帮助。 还有,安迪·海登派我去创造滚动平均线,这对我有很大的帮助。在


所以让我们一列一列地去做

  • 添加第1列:迄今为止的平均价格

    # Rolling avg, windows size is the size of the entire DataFrame, with minimum of 1
    df['rolling_avg'] = pd.rolling_mean(df.price, n, 1)
    
  • 添加第4列:最后4行的平均价格

    df['RA_wnd_4'] = pd.rolling_mean(df.price, 4, 1)
    
  • 在当前“blcok”(方向)中添加“change”列的col 2:CumSum()

    # Adding Helper column that shows when direction have been changed 
    df['dir_change'] = (df.direction.shift(1) != df.direction).astype(int)
    # Identify the DF "blocks" for every direction change 
    df['block'] = df.dir_change.cumsum()
    # Split the DF based on those bolcks 
    grouped = df.groupby('block')
    # Add Function that will cumsum() for a block, and call it 
    def f1(group):
         return DataFrame({'rolling_count' : group.cumsum()}) 
    
    df['rolling_count'] = grouped.change.apply(f1)
    
  • 添加第3列:当前“块”中的行号(方向)

    df['one'] = 1
    df['rolling_count'] = grouped.one.apply(f1)
    df = df.drop('one', axis=1)
    

完整代码:

import numpy.random as nprnd
from pandas import DataFrame
import pandas as pd

n = 10 # Number of samples
# Starting at 8:00 AM, set some (n) random prices between 4-5
df = DataFrame({'minute_id': range(480,480+n), 'price':(5-4) * nprnd.random(n) + 4 })
df['change'] = df.price - df.price.shift(1)
df['direction'] = df.change.map(lambda x: 0 if x == 0 else x/abs(x))
df = df.dropna()
#                     
# Col 1, rolling Avg over the entire DF
df['rolling_avg'] = pd.rolling_mean(df.price, n, 1) 
#                     
# Col 4, rolling Avg windows size of 4
df['RA_wnd_4'] = pd.rolling_mean(df.price, 4, 1)
#                     
# Helper code for cols 2, 3 
# Adding Helper column that shows when direction have been changed
df['dir_change'] = (df.direction.shift(1) != df.direction).astype(int)
# Identify the DF "blocks" for every direction change
df['block'] = df.dir_change.cumsum()
# Split the DF based on those bolcks
grouped = df.groupby('block')
# Add Function that will cumsum() for a block, and call it
def f1(group):
     return DataFrame({'rolling_count' : group.cumsum()})
df['one'] = 1
#                     
# Col 2, CumSum() of the 'change' column while in the current "blcok" (direction)
df['rolling_count'] = grouped.change.apply(f1)
#                     
# Col 3, Count in the current "block" (Direction)
df['rolling_count'] = grouped.one.apply(f1)
df = df.drop('one', axis=1)

print df

输出:

 minute_id  price   change  direction   rolling_avg     RA_wnd_4    dir_change  block   rolling_count
1   481     4.771701    0.474349    1   4.771701    4.771701    1   1   1
2   482     4.300078    -0.471623   -1  4.535889    4.535889    1   2   1
3   483     4.946744    0.646666    1   4.672841    4.672841    1   3   1
4   484     4.529403    -0.417340   -1  4.636981    4.636981    1   4   1
5   485     4.434598    -0.094805   -1  4.596505    4.552706    0   4   2
6   486     4.171169    -0.263429   -1  4.525616    4.520479    0   4   3
7   487     4.416980    0.245810    1   4.510096    4.388038    1   5   1
8   488     4.727078    0.310098    1   4.537219    4.437456    0   5   2
9   489     4.049097    -0.677981   -1  4.482983    4.341081    1   6   1

相关问题 更多 >

    热门问题