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

时间:2016-07-26 09:00:13

标签: python datetime pandas dataframe resampling

Pandas在版本18.1上更改了重新采样API。减少方法不再是重新采样方法的参数,但它们是它们自己的方法。

示例:

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方法。

当“如何”只是一个聚合函数时,一个answer已经涵盖了这种情况。我有更多想要进行上采样的案例。

例如:

#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)有这一行:

  

通过调度可用的任何函数都可以通过名称给出how参数,包括sum,mean,std,sem,max,min,median,first,last,ohlc。

how参数应该被弃用。

2 个答案:

答案 0 :(得分:4)

Resampler.agg的解决方案:

mangerid
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

答案 1 :(得分:2)

隔离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)()