首页 > 解决方案 > 在数据框中插入缺失的数字

问题描述

我有一个程序可以理想地每秒测量一次温度。然而,实际上这不会发生。有时,它会跳过一秒钟或中断 400 秒,然后决定重新开始录制。这在我的 2×n 数据框中留下了空白,理想情况下 n = 86400(一天中的秒数)。我想对其应用某种移动/滚动平均值以获得更好的绘图,但如果我对“原始”数据文件这样做,数据点的数量就会减少。此处显示,请注意 x 轴。我知道“好数据”看起来还不够好。我只是在玩一些价值观。

所以,我想实现一种数据清洗方法,将数据添加到数据框中。我想过,但不知道如何实现它。我是这样想的:

如果索引不等于时间,那么我们需要添加一个数字,时间=索引。如果这个差距只有1个值,那么前一个数字和下一个数字的平均值对我来说就可以了。但是如果它更大,比如缺少 100 秒,则需要做一个线性函数,这将稳定地增加或减少该值。

所以我猜一个训练集可能是这样的:

index   time   temp 
0       0      20.10
1       1      20.20
2       2      20.20
3       4      20.10
4       100    22.30

在这里,我想获取索引 3、时间 3 的值以及时间 = 4 和时间 = 100 之间缺失的值。对不起我的格式化技巧,希望清楚。

我将如何进行编程?

标签: pythonpandastime-series

解决方案


使用带有完整时间列的合并,然后interpolate

# Create your table
time = np.array([e for e in np.arange(20) if np.random.uniform() > 0.6])
temp = np.random.uniform(20, 25, size=len(time))
temps = pd.DataFrame([time, temp]).T
temps.columns = ['time', 'temperature']

>>> temps

   time  temperature
0   4.0    21.662352
1  10.0    20.904659
2  15.0    20.345858
3  18.0    24.787389
4  19.0    20.719487

以上是缺失时间数据生成的随机表。

# modify it
filled = pd.Series(np.arange(temps.iloc[0,0], temps.iloc[-1, 0]+1))
filled = filled.to_frame()
filled.columns = ['time'] # Create a fully filled time column
merged = pd.merge(filled, temps, on='time', how='left') # merge it with original, time without temperature will be null
merged.temperature = merged.temperature.interpolate() # fill nulls linearly.

# Alternatively, use reindex, this does the same thing.
final = temps.set_index('time').reindex(np.arange(temps.time.min(),temps.time.max()+1)).reset_index()
final.temperature = final.temperature.interpolate()

>>> merged # or final

    time  temperature
0    4.0    21.662352
1    5.0    21.536070
2    6.0    21.409788
3    7.0    21.283505
4    8.0    21.157223
5    9.0    21.030941
6   10.0    20.904659
7   11.0    20.792898
8   12.0    20.681138
9   13.0    20.569378
10  14.0    20.457618
11  15.0    20.345858
12  16.0    21.826368
13  17.0    23.306879
14  18.0    24.787389
15  19.0    20.719487

推荐阅读