2016-07-26 50 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