Pandas:合并具有不同时间戳的两个数据帧。传播缺少的值

2024-03-29 09:14:49 发布

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

我有两个数据帧,在同一时间段,但有非常不同的采样频率。我仍然想用两条简单的规则来合并这两条规则。你知道吗

选择更接近时间戳的值,然后将缺少的内容填入。日期并不重要,重要的只是时间戳。你知道吗

我给出了两个数据帧的示例

[140]:

data.index
[140]:
DatetimeIndex(['2019-02-08 07:53:26.380000', '2019-02-08 07:53:27.334000',
               '2019-02-08 07:53:27.653000', '2019-02-08 07:53:27.654000',
               '2019-02-08 07:53:27.655000', '2019-02-08 07:53:27.973000',
               '2019-02-08 07:53:27.974000', '2019-02-08 07:53:28.293000',
               '2019-02-08 07:53:28.304000', '2019-02-08 07:53:28.611000',
               ...
               '2019-02-08 14:41:03.128000', '2019-02-08 14:41:03.201000',
               '2019-02-08 14:41:03.260000', '2019-02-08 14:41:03.314000',
               '2019-02-08 14:41:03.429000', '2019-02-08 14:41:03.430000',
               '2019-02-08 14:41:03.748000', '2019-02-08 14:41:03.749000',
               '2019-02-08 14:41:03.752000', '2019-02-08 14:41:03.758000'],
              dtype='datetime64[ns]', name='Time', length=457631, freq=None)
[141]:

df.index
[141]:
Index(['07:53:26.380', '07:53:31.319', '07:53:31.825', '07:53:31.888',
       '07:53:31.889', '07:53:31.889', '07:53:31.988', '07:53:32.166',
       '07:53:32.287', '07:53:32.389',
       ...
       '14:40:43.759', '14:40:44.260', '14:40:44.761', '14:40:45.162',
       '14:40:45.662', '14:40:46.163', '14:40:46.664', '14:40:47.064',
       '14:40:47.064', '14:41:03.752'],
      dtype='object', name='Time', length=14641)

数据是最大的数据帧,我想包括df数据帧,如我所述:基于最接近的匹配时间戳,然后传播到下一个。你知道吗

到目前为止,我已经在网上搜索了很多,我已经找到了可以合并的代码。你知道吗

例如:

merge=pd.merge(data,df, how='inner', left_index=True, right_index=True)

pd.concat([data,df], join='inner', axis=1)

因为时间匹配不完全匹配,所以这些都不起作用(它们返回ofc空数据帧)。你知道吗

非常感谢你的帮助和建议。 当做 亚历克斯


Tags: 数据nametruedfdataindextime规则
1条回答
网友
1楼 · 发布于 2024-03-29 09:14:49

在将第二个数据帧的索引转换为适当的日期时间类型(现在正好是时间)之后,应该在pandas中使用merge\u asof方法。示例代码如下:

import pandas as pd
import numpy as np

#define the bigger dataframe
start = pd.Timestamp('2018-02-08 9:30:00')
end = pd.Timestamp('2018-02-08 15:45:00')
t = np.linspace(start.value, end.value, 100)
t = pd.to_datetime(t)
data=pd.DataFrame(index=t)
data['dummy_value1']=np.arange(len(data))

#define the smaller dataframe
start = pd.Timestamp('2018-02-08 14:30:00')
end = pd.Timestamp('2018-02-08 15:45:00')
t = np.linspace(start.value, end.value, 50)
t = pd.to_datetime(t)
df=pd.DataFrame(index=t)
df['dummy_value2']=10*np.arange(len(df))

#use merge_asof and verify the join has worked as expected by looking at last 10 rows
pd.merge_asof(data,df,left_index=True,right_index=True).tail(10)    

相关问题 更多 >