1

有 750k 行df15 列和一个pd.Timestampas indexcalled ts. 我以近乎实时的方式处理低至毫秒的实时数据。

现在我想将一些从更高时间分辨率派生的统计数据df_stats作为新列应用到大df. df_stats时间分辨率为 1 分钟。

$ df
+----------------+---+---------+
| ts             | A | new_col |
+----------------+---+---------+
| 11:33:11.31234 | 1 | 81      |
+----------------+---+---------+
| 11:33:11.64257 | 2 | 81      |
+----------------+---+---------+
| 11:34:10.12345 | 3 | 60      |
+----------------+---+---------+
$ df_stats
+----------------+----------------+
| ts             | new_col_source |
+----------------+----------------+
| 11:33:00.00000 | 81             |
+----------------+----------------+
| 11:34:00.00000 | 60             |
+----------------+----------------+

目前我有下面的代码,但它效率低下,因为它需要遍历完整的数据。

我想知道使用pd.cut,bin是否有更简单的解决方案pd.Grouper?或者其他什么来合并两个索引上的时间段?

df_stats['ts_timeonly'] = df.index.map(lambda x: x.replace(second=0, microsecond=0))
df['ts_timeonly'] = df.index.map(lambda x: x.replace(second=0, microsecond=0))
df = df.merge(df_stats, on='ts_timeonly', how='left', sort=True, suffixes=['', '_hist']).set_index('ts')
4

1 回答 1

2

让我们尝试一些新的东西reindex

df_stats=df_stats.set_index('ts').reindex(df['ts'], method='nearest')
df_stats.index=df.index

df=pd.concat([df,df_stats],axis=1)

或者

df=pd.merge_asof(df, df_stats, on='ts',direction='nearest')
于 2020-04-24T00:51:49.627 回答