pandas 有条件地添加插值器函数作为新列
pandas adding a interpolator function conditionally as a new column
我创建了一系列 5 个 scipy
cubic spline(插值器类型)对象,如下所示:
from scipy.interpolate import CubicSpline
def spline3(df, col1, col2):
x, y = df[col1].values, df[col2].values
cs = CubicSpline(x, y, bc_type='natural')
return cs
# indexed series of spline obj
splines = avg_df.groupby('group').apply(spline3, 'tenor', 'mid')
导致:
splines
Out[129]:
group
A <scipy.interpolate._cubic.CubicSpline object a...
B <scipy.interpolate._cubic.CubicSpline object a...
C <scipy.interpolate._cubic.CubicSpline object a...
D <scipy.interpolate._cubic.CubicSpline object a...
E <scipy.interpolate._cubic.CubicSpline object a...
dtype: object
即,它们将为相同的输入 x
产生不同的插值,如下所示。如何应用它将这个最小数据集说成一个新列:
toy = pd.DataFrame({
'group': ['A', 'A', 'E'],
'months': [11.04, 11.89, 7.51]
})
toy
Out[132]:
group months
0 A 11.04
1 A 11.89
2 E 7.51
类似 toy['interpolated'] = splines[toy['MMD'](toy['months']
的东西如下:
splines['A'](7)
Out[135]: array(0.90897722)
splines['E'](7)
Out[136]: array(1.74683114)
正在考虑 apply
\ pipe
或 np.select
但周五这么晚我才想起来。
我认为您可以将 .apply
与 lambda row: func(row)
一起使用,其中 func(row) 的形式为 splines[row['group']](row['month'])
:
toy['spline_x'] = toy.apply(lambda row: splines[row['group']](row['month'), axis=1)
我创建了一系列 5 个 scipy
cubic spline(插值器类型)对象,如下所示:
from scipy.interpolate import CubicSpline
def spline3(df, col1, col2):
x, y = df[col1].values, df[col2].values
cs = CubicSpline(x, y, bc_type='natural')
return cs
# indexed series of spline obj
splines = avg_df.groupby('group').apply(spline3, 'tenor', 'mid')
导致:
splines
Out[129]:
group
A <scipy.interpolate._cubic.CubicSpline object a...
B <scipy.interpolate._cubic.CubicSpline object a...
C <scipy.interpolate._cubic.CubicSpline object a...
D <scipy.interpolate._cubic.CubicSpline object a...
E <scipy.interpolate._cubic.CubicSpline object a...
dtype: object
即,它们将为相同的输入 x
产生不同的插值,如下所示。如何应用它将这个最小数据集说成一个新列:
toy = pd.DataFrame({
'group': ['A', 'A', 'E'],
'months': [11.04, 11.89, 7.51]
})
toy
Out[132]:
group months
0 A 11.04
1 A 11.89
2 E 7.51
类似 toy['interpolated'] = splines[toy['MMD'](toy['months']
的东西如下:
splines['A'](7)
Out[135]: array(0.90897722)
splines['E'](7)
Out[136]: array(1.74683114)
正在考虑 apply
\ pipe
或 np.select
但周五这么晚我才想起来。
我认为您可以将 .apply
与 lambda row: func(row)
一起使用,其中 func(row) 的形式为 splines[row['group']](row['month'])
:
toy['spline_x'] = toy.apply(lambda row: splines[row['group']](row['month'), axis=1)