我發現自己將函數應用於TimeSeries的值和索引。我這樣做的方法是構建一個DataFrame中的值和和TimeSeries的索引,然後將一個函數應用於DataFrame。將函數應用於系列值和索引
# imports
import pandas as pd
import numpy as np
# Set up some input time series
dates = pd.date_range('2012-04-01', periods=500,freq='MS')
ts = pd.Series(np.arange(500), index=dates)
# Build data frame of values and index
tmp = pd.concat([ts, ts.index.to_series()], join='outer', axis=1)
# Example function to apply
f = lambda x: x[0]/4 if x[1].month % 3 == 1 else 0
# Apply function
out = tmp.apply(f, axis=1)
我有一個偷渡懷疑,這是不是解決這個最優雅/有效的方式,但無法找到在docs任何建議更好的路線。有任何想法嗎?
這不起作用(儘管它看起來應該!)。當我使用你的解決方案時,我可以在's.index.month%3 == 1'和's/4'處找到's.index.month%3!= 1';我分別想要's/4'和'0' –
@Jeff這是錯誤的,第三個參數是'inplace',所以'0'在這裏意味着'False',實際上是默認值。 –
好吧,我認爲很容易啓用,但讓我考慮一下。你也可以做鏈接祿(相同的想法) – Jeff