如何扩展数据(插值?)

时间:2018-08-22 01:56:11

标签: python pandas dataframe

我想通过在数据帧之间插入数据来扩展最长的列长度,以匹配最长列的长度。

我不熟悉正确的术语,因此请更正我的词汇或告知我如何更好地进行交流。我相信pd.DataFrame.resample()是答案,但是在彻底阅读文档之后,我还不确定如何“扩展”列。

我有一个像这样的数据框:

2000-01-01 00:00:00    0  0    0
2000-01-01 00:01:00    1  1    3
2000-01-01 00:02:00    2  2    5
2000-01-01 00:03:00    3  3    3
2000-01-01 00:04:00    4  nan  nan
2000-01-01 00:05:00    5  nan  nan
2000-01-01 00:06:00    6  nan  nan

我想“扩展”第二列,使它的时间一样长,但不会丢失其任何数据。执行所需的方法后,希望数据看起来像这样:

2000-01-01 00:00:00    0  0    0
2000-01-01 00:01:00    1  0.5  1.5
2000-01-01 00:02:00    2  1    3
2000-01-01 00:03:00    3  1.5  4
2000-01-01 00:04:00    4  2    5
2000-01-01 00:05:00    5  2.5  4
2000-01-01 00:06:00    6  3    3

最终目标是平均每个索引上数据帧中的所有列。如果有比“扩展”更短的列更简单的方法,请告诉我。我希望结果表看起来像这样:

2000-01-01 00:00:00    0  
2000-01-01 00:01:00    1
2000-01-01 00:02:00    2
2000-01-01 00:03:00    2.8333
2000-01-01 00:04:00    3.6667
2000-01-01 00:05:00    3.8333
2000-01-01 00:06:00    4

很多Mahalo:)

编辑:我已经通过添加第三列更改了发布的原始数据。我意识到我的原始帖子并没有反映出我需要一种适用于任意增加和减少且独立于其他列的列的解决方案。

1 个答案:

答案 0 :(得分:1)

数据df

                 time  col1  col2
0 2000-01-01 00:00:00     0   0.0
1 2000-01-01 00:01:00     1   1.0
2 2000-01-01 00:02:00     2   2.0
3 2000-01-01 00:03:00     3   3.0
4 2000-01-01 00:04:00     4   NaN
5 2000-01-01 00:05:00     5   NaN
6 2000-01-01 00:06:00     6   NaN

代码:

# get min/max values in col2
col2_min = df.col2.min()
col2_max = df.col2.max()

# restart col2 with min/max value only,
# and then interpolate values based on col1 values
df.col2 = np.nan
df.loc[df.col1.min(), 'col2'] = col2_min
df.loc[df.col1.max(), 'col2'] = col2_max
df.col2 = df.set_index('col1').col2.interpolate(method='index')
df['col3'] = (df.col1 + df.col2) / 2

输出:

                 time  col1  col2  col3
0 2000-01-01 00:00:00     0   0.0  0.00
1 2000-01-01 00:01:00     1   0.5  0.75
2 2000-01-01 00:02:00     2   1.0  1.50
3 2000-01-01 00:03:00     3   1.5  2.25
4 2000-01-01 00:04:00     4   2.0  3.00
5 2000-01-01 00:05:00     5   2.5  3.75
6 2000-01-01 00:06:00     6   3.0  4.50

我假设col2的值与col1成线性比例,因此首先确定minmax中的col1col2值并尝试匹配它们。然后根据col2值内插col1值。