我想在较小数据帧时间序列的每一列上分别进行样条线插值,以创建尺寸更大的解析数据帧时间序列,其尺寸大于原始数据。

因此,理想情况下,代码应类似于以下内容(在伪代码中):

from scipy.interpolate import UnivariateSpline as Spline
import pandas as pd

few_times = pd.date_range(t0, t1, periods=10)
few_times_for_spline = few_times.values.astype('float')
many_times = pd.date_range(t0, t1, periods=1000)
many_times_for_spline = many_times.values.astype('float')

df_to_interp = pd.DataFrame(randn(10,100), index=few_times)

def do_spline(col):
    return Spline(few_times_for_spline, col)(many_times_for_spline)

df_to_interp.apply(do_spline)


但这给了我错误,因为这些尺寸不能强制到原始数据框尺寸。我有点困惑为什么它不起作用,因为df.groupby()。apply()允许更改返回值的尺寸。

到目前为止,我的解决方案是使用纯numpy并使用其功能apply_along_axis

pd.DataFrame(apply_along_axis(do_spline,
                              0,
                              df_to_interp.values),
             index=many_times,
             columns=df_to_interp.columns)


但我想知道是否没有更多的panda-esque解决方案?

最佳答案

从.13开始,您应该能够使用reindexinterpolate进行此操作(只要您具有scipy)。

In [54]: df = pd.DataFrame(np.random.randn(100, 4).cumsum(0)
, index=pd.DatetimeIndex(start='2010-01-01', freq='s', periods=100))

In [55]: many_idx = pd.DatetimeIndex(start=df.index[0], end=df.index[-1], freq='ms')

In [56]: df.index
Out[56]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2010-01-01 00:00:00, ..., 2010-01-01 00:01:39]
Length: 100, Freq: S, Timezone: None

In [57]: many_idx
Out[57]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2010-01-01 00:00:00, ..., 2010-01-01 00:01:39]
Length: 99001, Freq: L, Timezone: None


因此,现在的想法是将reindex df转换为many_idx,并用样条曲线填充生成的NaN(每列分别)。在pandas / scipy中的某个地方似乎存在一个错误,在其中仅执行df.reindex(many_idx).interpolate(method='spline', order=1)会抱怨无法从dtype('<M8[ns]') to dtype('float64')强制转换索引dtype,因此,一种变通方法:

In [61]: df.reindex(many_idx).reset_index().interpolate(method='spline', order=1).set_index('index')
Out[61]:
                                   0         1         2         3
index
2010-01-01 00:00:00        -0.623775  0.069668 -0.010604 -0.201834
2010-01-01 00:00:00.001000 -0.621875  0.569733  0.081842 -0.278664
2010-01-01 00:00:00.002000 -0.621800  0.570461  0.081998 -0.278531
2010-01-01 00:00:00.003000 -0.621725  0.571190  0.082153 -0.278397
2010-01-01 00:00:00.004000 -0.621651  0.571918  0.082308 -0.278263
2010-01-01 00:00:00.005000 -0.621576  0.572647  0.082463 -0.278130
2010-01-01 00:00:00.006000 -0.621502  0.573376  0.082618 -0.277996
2010-01-01 00:00:00.007000 -0.621427  0.574104  0.082774 -0.277862
2010-01-01 00:00:00.008000 -0.621352  0.574833  0.082929 -0.277729
2010-01-01 00:00:00.009000 -0.621278  0.575561  0.083084 -0.277595
2010-01-01 00:00:00.010000 -0.621203  0.576290  0.083239 -0.277462
2010-01-01 00:00:00.011000 -0.621128  0.577018  0.083395 -0.277328


看起来像您想要的吗?

关于python - 寻找没有形状限制的dataframe.apply(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20851838/

10-12 22:26