如何将每次更改的一条记录转换为连续数据?



我的数据是这样的:
print(df)

DateTime,      Status
'2021-09-01',  0
'2021-09-05',  1
'2021-09-07',  0
我需要它看起来像这样:
print(df_desired)
DateTime,      Status
'2021-09-01',  0
'2021-09-02',  0
'2021-09-03',  0
'2021-09-04',  0
'2021-09-05',  1
'2021-09-06',  1
'2021-09-07',  0

现在我用熊猫来完成这个任务,像这样:

new_index = pd.DataFrame(index = pd.date_range(df.index[0], df.index[-1], freq='D'))
df = new_index.join(df).ffill()

任何列中第一个记录之前的缺失值使用该列中第一个记录的逆来推算,因为它是二进制的,只显示更改点,这保证是正确的。

对于我的理解,我想要的数据框架包含"continuous"数据,但我不确定该如何称呼源数据中的数据结构。

问题:
当我对一个频率为每秒一条记录的数据帧这样做时,我想加载一年的数据,我的内存溢出(需要92GB, ~60GB可用)。我不确定是否有一个标准的过程,而不是我的解决方案,我不知道的名字,不能找到使用谷歌或我使用错误的连接方法,但这似乎非常低效,结果数据帧只有几个100兆字节后,这个操作。任何关于这个的反馈将是伟大的!

使用DataFrame.asfreqDatetimeIndex:

df = df.set_index('DateTime').asfreq('d', method='ffill').reset_index()
print (df)
DateTime  Status
0 2021-09-01       0
1 2021-09-02       0
2 2021-09-03       0
3 2021-09-04       0
4 2021-09-05       1
5 2021-09-06       1
6 2021-09-07       0

你可以使用这个管道:

(df.set_index('DateTime')
.reindex(pd.date_range(df['DateTime'].min(), df['DateTime'].max()))
.rename_axis('DateTime')
.ffill(downcast='infer')
.reset_index()
)

输出:

DateTime  Status
0 2021-09-01       0
1 2021-09-02       0
2 2021-09-03       0
3 2021-09-04       0
4 2021-09-05       1
5 2021-09-06       1
6 2021-09-07       0

输入:

DateTime  Status
0 2021-09-01       0
1 2021-09-05       1
2 2021-09-07       0

最新更新