我有一些数据框:
time data
1 1
2 2
3.5 3
4.22 5
9.1 3
10.2 4
时间肯定会增加。
我想要一个数据帧,其中时间列在给定范围(start, stop, step)
内插,并通过某种内插方法对数据列进行相应采样。
我希望进行推断,这意味着我希望start
或stop
能够小于最小时间值或大于最大时间值。
我该怎么做?
我可以接受numpy的解决方案,但如果可能的话,我宁愿只呆在熊猫里面。
答案 0 :(得分:0)
这是一种方法,该方法是使用所需的Time
序列构建新的数据帧,然后将merge_asof
与interpolate
一起使用,并在data
列中填充它:
step=.2
ix = np.arange(df.time.min(), df.time.max(), step)
out = pd.DataFrame({'time':ix})
out = pd.merge_asof(out, df,
on='time',
direction='nearest',
tolerance=df.time.mod(step).max())
out['data'] = out['data'].interpolate()
print(out)
time data
0 1.0 1.000000
1 1.2 1.000000
2 1.4 1.250000
3 1.6 1.500000
4 1.8 1.750000
5 2.0 2.000000
6 2.2 2.000000
7 2.4 2.166667
8 2.6 2.333333
9 2.8 2.500000
10 3.0 2.666667
11 3.2 2.833333
12 3.4 3.000000
13 3.6 3.000000
14 3.8 3.666667
15 4.0 4.333333
16 4.2 5.000000
17 4.4 5.000000
18 4.6 4.913043
19 4.8 4.826087
....
答案 1 :(得分:0)
使用自定义插值功能。遵循以下原则:
from scipy.interpolate import interp1d
def interpolator(g: pd.Series):
x = [...]
y = [...]
interpolated_array = interp1d(x, y, bounds_error=False, fill_value=0)(g)
return interpolated_array
grouped = df.groupby('column_a')
df['column_intepolated'] = grouped['column_b'].transform(interpolator)
如果您想尝试一下,并努力适应您的数据,请发表评论,我将在此处发布。