Pandas应用于滚动多列输出

iugsix8n  于 2023-08-01  发布在  其他
关注(0)|答案(3)|浏览(103)

我正在编写一个代码,它将向返回多列的函数应用滚动窗口。
输入:Pandas系列
预期的输出:3列 Dataframe

def fun1(series, ):
    # Some calculations producing numbers a, b and c
    return {"a": a, "b": b, "c": c} 

res.rolling('21 D').apply(fun1)

字符串
res内容:

time
2019-09-26 16:00:00    0.674969
2019-09-26 16:15:00    0.249569
2019-09-26 16:30:00   -0.529949
2019-09-26 16:45:00   -0.247077
2019-09-26 17:00:00    0.390827
                         ...   
2019-10-17 22:45:00    0.232998
2019-10-17 23:00:00    0.590827
2019-10-17 23:15:00    0.768991
2019-10-17 23:30:00    0.142661
2019-10-17 23:45:00   -0.555284
Length: 1830, dtype: float64


错误代码:

TypeError: must be real number, not dict


我尝试过的:

  • 更改原始值= Apply中的True
  • 在apply中使用lambda函数
  • 返回fun 1中的结果作为lists/numpy arrays/dataframe/series。

我也读过许多关于SO的文章,说几句:

但是没有一个解决方案可以解决这个问题。
有没有直接的解决办法?

vsnjm48y

vsnjm48y1#

下面是一个hacky的答案,使用rolling生成一个DataFrame:

import pandas as pd
import numpy as np

dr = pd.date_range('09-26-2019', '10-17-2019', freq='15T')
data = np.random.rand(len(dr))

s = pd.Series(data, index=dr)

output = pd.DataFrame(columns=['a','b','c'])

row = 0

def compute(window, df):
    global row
    a = window.max()
    b = window.min()
    c = a - b
    df.loc[row,['a','b','c']] = [a,b,c]
    row+=1    
    return 1
    
s.rolling('1D').apply(compute,kwargs={'df':output})

output.index = s.index

字符串
似乎rollingapply函数总是期望返回一个数字,以便根据计算立即生成一个新的Series。
我通过创建一个新的output DataFrame(带有所需的输出列)并在函数中写入该数据来解决这个问题。我不确定是否有一种方法可以在滚动对象中获取索引,所以我使用global来增加写入新行的计数。根据上面的观点,你需要return一些数字。因此,虽然实际上rolling操作返回一系列1,但output被修改:

In[0]:
s

Out[0]:
2019-09-26 00:00:00    0.106208
2019-09-26 00:15:00    0.979709
2019-09-26 00:30:00    0.748573
2019-09-26 00:45:00    0.702593
2019-09-26 01:00:00    0.617028
  
2019-10-16 23:00:00    0.742230
2019-10-16 23:15:00    0.729797
2019-10-16 23:30:00    0.094662
2019-10-16 23:45:00    0.967469
2019-10-17 00:00:00    0.455361
Freq: 15T, Length: 2017, dtype: float64

In[1]:
output

Out[1]:
                           a         b         c
2019-09-26 00:00:00  0.106208  0.106208  0.000000
2019-09-26 00:15:00  0.979709  0.106208  0.873501
2019-09-26 00:30:00  0.979709  0.106208  0.873501
2019-09-26 00:45:00  0.979709  0.106208  0.873501
2019-09-26 01:00:00  0.979709  0.106208  0.873501
                      ...       ...       ...
2019-10-16 23:00:00  0.980544  0.022601  0.957943
2019-10-16 23:15:00  0.980544  0.022601  0.957943
2019-10-16 23:30:00  0.980544  0.022601  0.957943
2019-10-16 23:45:00  0.980544  0.022601  0.957943
2019-10-17 00:00:00  0.980544  0.022601  0.957943

[2017 rows x 3 columns]


这感觉更像是对rolling的利用,而不是预期的用途,所以我很有兴趣看到一个更优雅的答案。

UPDATE:感谢@JuanPi,您可以使用this answer获取滚动窗口索引。因此,非global的答案可能如下所示:

def compute(window, df):
    a = window.max()
    b = window.min()
    c = a - b
    df.loc[window.index.max(),['a','b','c']] = [a,b,c]  
    return 1

s4n0splo

s4n0splo2#

这个黑客似乎对我有效,尽管滚动的附加特性不能应用到这个解决方案中。然而,由于多处理,应用程序的速度明显更快。

from multiprocessing import Pool
import functools

def apply_fn(indices, fn, df):
    return fn(df.loc[indices])
              
    
def rolling_apply(df, fn, window_size, start=None, end=None):
    """
    The rolling application of a function fn on a DataFrame df given the window_size
    """
    x = df.index
    if start is not None:
        x = x[x >= start]
    if end is not None:
        x = x[x <= end]
    if type(window_size) == str:
        delta = pd.Timedelta(window_size)
        index_sets = [x[(x > (i - delta)) & (x <= i)] for i in x]
    else: 
        assert type(window_size) == int, "Window size should be str (representing Timedelta) or int"
        delta = window_size
        index_sets = [x[(x > (i - delta)) & (x <= i)] for i in x]
    
    with Pool() as pool:
        result = list(pool.map(functools.partial(apply_fn, fn=fn, df=df), index_sets))
    result = pd.DataFrame(data=result, index=x)
        
    return result

字符串
将上述函数设置好后,插入函数以滚动到自定义rolling_function中。

result = rolling_apply(res, fun1, "21 D")


结果内容:

a           b           c
time            
2019-09-26 16:00:00 NaN         NaN         NaN
2019-09-26 16:15:00 0.500000    0.106350    0.196394
2019-09-26 16:30:00 0.500000    0.389759    -0.724829
2019-09-26 16:45:00 2.000000    0.141436    -0.529949
2019-09-26 17:00:00 6.010184    0.141436    -0.459231
... ... ... ...
2019-10-17 22:45:00 4.864015    0.204483    -0.761609
2019-10-17 23:00:00 6.607717    0.204647    -0.761421
2019-10-17 23:15:00 7.466364    0.204932    -0.761108
2019-10-17 23:30:00 4.412779    0.204644    -0.760386
2019-10-17 23:45:00 0.998308    0.203039    -0.757979
1830 rows × 3 columns


注意事项:

  • 此实现同时适用于Series和DataFrame输入
  • 此实现适用于时间窗口和整数窗口
  • fun1返回的结果甚至可以是list、numpy数组、series或字典
  • window_size只考虑最大窗口大小,因此所有低于window_size的起始索引将使其窗口包括直到起始元素的所有元素。
  • apply函数不应嵌套在rolling_apply函数中,因为pool.map不能接受本地函数或lambda函数,因为它们不能根据multiprocessing库进行“pickle”
pcww981p

pcww981p3#

你可以分别使用rolling()和apply()**来获得多个列。从原始Dataframe创建一个Rolling Dataframe一次,然后多次使用.apply()。
对于名为“df”的数据框:

windows = df.rolling(window_size)
a_series = windows.apply(lambda x: find_a_for_single_window(x))
b_series = windows.apply(lambda x: find_b_for_single_window(x))
c_series = windows.apply(lambda x: find_c_for_single_window(x))

字符串

相关问题