我是熊猫的新手,我不知道最好的方法.
我有两个文件,我放在两个不同的数据帧中:
>> frame1.head()
Out[64]:
Date and Time Sample Unnamed: 2
0 05/18/2017 08:38:37:490 163.7 NaN
1 05/18/2017 08:39:37:490 164.5 NaN
2 05/18/2017 08:40:37:490 148.7 NaN
3 05/18/2017 08:41:37:490 111.2 NaN
4 05/18/2017 08:42:37:490 83.6 NaN
>>frame2.head()
Out[66]:
Date and Time Sample Unnamed: 2
0 05/18/2017 08:38:38:490 7.5 NaN
1 05/18/2017 08:39:38:490 7.5 NaN
2 05/18/2017 08:40:38:490 7.5 NaN
3 05/18/2017 08:41:38:490 7.5 NaN
4 05/18/2017 08:42:38:490 7.5 NaN
我需要“合并”第1帧中的任何行,第2帧中的任何行,彼此相差一秒.
例如,
第1帧的这一行:
0 05/18/2017 08:38:37:490 163.7 NaN
在第2帧的这一行的一秒内:
0 05/18/2017 08:38:38:490 7.5 NaN
所以当他们“合并”时输出应该是这样的:
0 05/18/2017 08:38:37:490 163.7 7.5 NaN NaN
换句话说,一行将其时间替换为另一行,并且仅附加所有剩余列
我最接近的是做类似的事情:
d3 = pd.merge(frame1, frame2, on='Date and Time (MM/DD/YYYY HH:MM:SS:sss)', how='outer')
>>d3.head()
Date and Time Sample_x Unnamed: 2_x Sample_y Unnamed: 2_y
0 05/18/2017 08:38:37:490 163.7 NaN NaN NaN
1 05/18/2017 08:39:37:490 164.5 NaN NaN NaN
2 05/18/2017 08:40:37:490 148.7 NaN NaN NaN
3 05/18/2017 08:41:37:490 111.2 NaN NaN NaN
4 05/18/2017 08:42:37:490 83.6 NaN NaN NaN
但是,这不是一个有条件的合并..我需要合并,如果它们在一秒之内,而不是完全相同.
我知道我可以将时间与以下内容进行比较:
def compare_time(temp, sec=1):
return abs(current - temp) <= datetime.timedelta(seconds=sec)
然后使用.apply()或其他东西……但我不知道如何将所有这些拼凑在一起
编辑:看起来pd.merge_asof做得很好,但我还需要保留最终帧中不匹配/合并的行
编辑2:
df1 = pd.DataFrame({ 'datetime':pd.date_range('1-1-2017', periods= 4,freq='s'),
'sample': np.arange(4)+100 })
df2 = pd.DataFrame({ 'datetime':pd.date_range('1-1-2017', periods=4,freq='300ms'),
'sample': np.arange(4) })
blah = pd.merge_asof( df2, df1, on='datetime', tolerance=pd.Timedelta('1s') ) \
.append(df1.rename(columns={'sample':'sample_x'})).drop_duplicates('sample_x')
blah
收益:
datetime sample_x sample_y
0 2017-01-01 00:00:00.000 0 100.0
1 2017-01-01 00:00:00.300 1 100.0
2 2017-01-01 00:00:00.600 2 100.0
3 2017-01-01 00:00:00.900 3 100.0
0 2017-01-01 00:00:00.000 100 NaN
1 2017-01-01 00:00:01.000 101 NaN
2 2017-01-01 00:00:02.000 102 NaN
3 2017-01-01 00:00:03.000 103 NaN
注意它保留了原始行索引(零列出两次)..