2016-07-26 42 views
3

熊猫在版本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已经涵盖了“how”只是一个聚合函数的情况。我更想到要执行上采样的情况。

E.g:

#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静止(2016年7月26日)具有这一行:

经由任何可用的调度功能可以给予通过名称,包括总和如何参数,平均值,标准,SEM,最大值,最小值,中位数,第一位,最后一位,ohlc。

但是how参数应该被弃用。

回答

1

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

解决方案与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 
+0

非常简单和优雅! – MaxU

+0

@MaxU - 谢谢。 – jezrael