熊猫:合并两个带有不同时间戳的数据帧。传播缺失值

时间:2019-05-22 16:39:54

标签: python pandas dataframe merge

我有两个数据帧,它们处于相同的时间段,但采样频率却大不相同。我仍然希望将这两个规则与两个简单规则合并。

选择一个接近时间戳的值,然后填写所有缺少的值。日期并不只是时间戳而重要。

我举一个例子说明两个数据框的样子

[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)

由于时间匹配不完全匹配,这些都不起作用(它们返回空数据帧)。

您的帮助和建议不胜感激。 问候 亚历克斯

1 个答案:

答案 0 :(得分:0)

在将第二个数据帧的索引转换为适当的日期时间类型(现在只是时间)之后,应该在熊猫中使用merge_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)