gpt4 book ai didi

python - 使用多列进行 Pandas 滚动应用

转载 作者:行者123 更新时间:2023-12-01 23:35:48 27 4
gpt4 key购买 nike

我正在尝试在多列上使用pandas.DataFrame.rolling.apply()滚动函数。Python版本是3.7,pandas是1.0.2。

import pandas as pd

#function to calculate
def masscenter(x):
print(x); # for debug purposes
return 0;

#simple DF creation routine
df = pd.DataFrame( [['02:59:47.000282', 87.60, 739],
['03:00:01.042391', 87.51, 10],
['03:00:01.630182', 87.51, 10],
['03:00:01.635150', 88.00, 792],
['03:00:01.914104', 88.00, 10]],
columns=['stamp', 'price','nQty'])
df['stamp'] = pd.to_datetime(df2['stamp'], format='%H:%M:%S.%f')
df.set_index('stamp', inplace=True, drop=True)

'stamp' 是单调且唯一的,'price' 是 double 且不包含 NaN,'nQty' 是整数且还包含没有 NaN。

因此,我需要计算滚动“质心”,即 sum(price*nQty)/sum(nQty)

到目前为止我尝试过的:

df.apply(masscenter, axis = 1)

masscenter 在一行中被调用 5 次,输出如下

price     87.6
nQty 739.0
Name: 1900-01-01 02:59:47.000282, dtype: float64

这是 masscenter 所需的输入,因为我可以使用 x[0], x 轻松访问 pricenQty [1]。但是,我坚持使用rolling.apply()阅读文档 DataFrame.rolling()rolling.apply()我认为在 rolling() 中使用 'axis' 和在 apply 中使用 'raw' 可以实现类似的行为。一种幼稚的方法

rol = df.rolling(window=2)
rol.apply(masscenter)

逐行打印(增加行数直至窗口大小)

stamp
1900-01-01 02:59:47.000282 87.60
1900-01-01 03:00:01.042391 87.51
dtype: float64

然后

stamp
1900-01-01 02:59:47.000282 739.0
1900-01-01 03:00:01.042391 10.0
dtype: float64

因此,列被单独传递到 masscenter (预期)。

遗憾的是,在文档中几乎没有任何有关'axis'的信息。然而,下一个变体显然是

rol = df.rolling(window=2, axis = 1)
rol.apply(masscenter)

永远不会调用masscenter并在rol.apply(..)中引发ValueError

> Length of passed values is 1, index implies 5

我承认,由于缺乏文档,我不确定 'axis' 参数及其工作原理。这是问题的第一部分:这是怎么回事?如何正确使用“轴”?它的设计目的是什么?

当然,之前已经有答案了,即:

How-to-apply-a-function-to-two-columns-of-pandas-dataframe
它适用于整个 DataFrame,而不是 Rolling。

How-to-invoke-pandas-rolling-apply-with-parameters-from-multiple-column
答案建议编写我自己的滚动函数,但对我来说罪魁祸首与 comments 中所问的相同。 :如果需要对非统一时间戳使用偏移窗口大小(例如 '1T')怎么办?
我不喜欢从头开始重新发明轮子的想法。另外,我想用 pandas 来做所有事情,以防止从 pandas 获得的集合和“自制卷”之间出现不一致。这个问题还有另一个答案,建议单独填充数据帧并计算我需要的任何内容,但它不会起作用:存储数据的大小将是巨大的。这里提出了相同的想法:
Apply-rolling-function-on-pandas-dataframe-with-multiple-arguments

此处发布了另一个问答
Pandas-using-rolling-on-multiple-columns
这很好,而且最接近我的问题,但同样,不可能使用偏移窗口大小 (window = '1T')。

在 pandas 1.0 发布之前就已经提出了一些答案,并且考虑到文档可能会更好,我希望现在可以同时滚动多个列。

问题的第二部分是:是否有可能使用具有偏移窗口大小的 pandas 1.0.x 同时滚动多个列?

非常感谢。

最佳答案

这个怎么样:

def masscenter(ser):
print(df.loc[ser.index])
return 0

rol = df.price.rolling(window=2)
rol.apply(masscenter, raw=False)

它使用滚动逻辑从任意列获取子集。 raw=False 选项为您提供这些子集的索引值(作为系列提供给您),然后您使用这些索引值从原始 DataFrame 中获取多列切片。

关于python - 使用多列进行 Pandas 滚动应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60736556/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com