用重复的值填补Pandas数据帧中的空白

2024-04-30 01:51:49 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有一个如下所示的数据帧

timestamp   v
1           5
2           6
6           7
8           8

Pandas中是否有一种方法可以创建一个数据帧来完成丢失的时间戳,并使用最后分配的v值,而不必在每行之间进行迭代

timestamp   v
1           5
2           6
3           6
4           6
5           6
6           7
7           7
8           8

我能够通过在两行之间迭代并检测时间戳中缺少的值并添加v的最后一个值来解决这个问题,但是速度太慢了


Tags: 数据方法pandas时间速度timestamp检测时间
2条回答

您可以使用merge_asof

# consider `pd.date_range` to generate range of timestamps
all_time = pd.DataFrame({'timestamp':np.arange(df.timestamp.iloc[0], 
                                               df.timestamp.iloc[-1]+1)
                        })
pd.merge_asof(all_time, df, on='timestamp', direction='backward')

输出:

   timestamp  v
0          1  5
1          2  6
2          3  6
3          4  6
4          5  6
5          6  7
6          7  7
7          8  8

代码

df = df.set_index('timestamp')
df = df.reindex(np.arange(df.index[0], 1+df.index[-1])).ffill().reset_index().astype(int)

输出

    timestamp   v
0   1           5
1   2           6
2   3           6
3   4           6
4   5           6
5   6           7
6   7           7
7   8           8

解释

我们将索引设置为timestamp,然后根据索引的第一个和最后一个值重新索引,然后向前填充值

相关问题 更多 >