使用变量中的方法在 pandas 中重新采样

resample in pandas with the method in a variable

Pandas 在版本 18.1 上更改了其重采样 API。 reduction 方法不再是 resample 方法的参数,而是它们自己的方法。

示例:

import pandas as pd
import numpy as np

rng = pd.date_range('1/1/2012', periods=100, freq='S')
ts = pd.Series(np.random.randint(0, 500, len(rng)), index=rng)

#Old API
ts.resample('5Min', how='sum')

#New API
ts.resample('5Min').sum()

我有一些代码是这样的:

def my_func(my_series, how="sum"):
    #Do some stuff before
    my_series.resample('5Min' how=how)

如何使用新的 API 来实现?我希望 my_func 能够使用不同的缩减方法调用 resample 方法。

一个 已经涵盖了 "how" 只是一个聚合函数的情况。我想到了更多我们想要执行上采样的情况。

例如:

#Old API:
ts.resample('250L', fill_method='ffill')
#New API
ts.resample('250L').ffill()

请注意,在我的真实代码中,我有一些更接近于此的内容:

def my_func(dummy_df, freq="10Min", how="last", label="right", closed="right", fill_method="ffill"):
    dummy_df.resample(freq, how=how, label=label, closed=closed, fill_method=fill_method)

想用新的API再写一遍

令人困惑的是 documentation 仍然 (26.07.2016) 有这条线:

Any function available via dispatching can be given to the how parameter by name, including sum, mean, std, sem, max, min, median, first, last, ohlc.

但是 how 参数应该被弃用。

Resampler.agg 的解决方案:

print (ts.resample('5Min').agg('sum'))

print (ts.resample('5Min').sum())
2012-01-01    24223
Freq: 5T, dtype: int32

print (ts.resample('5Min').agg('sum'))
2012-01-01    24223
Freq: 5T, dtype: int32

所以自定义函数是:

def my_func(my_series, how="sum"):
    #Do some stuff before
    return my_series.resample('5Min').agg(how)

print (my_func(ts))
2012-01-01    24223
Freq: 5T, dtype: int32

分离 howfill_method 并通过 getattr:

def my_func(dummy_df, freq="10Min", how="last",
            label="right", closed="right", fill_method="ffill"):
    resample = dummy_df.resample(freq, label=label, closed=closed)
    return getattr(getattr(resample, how)(), fill_method)()