【发布时间】:2016-02-12 15:44:23
【问题描述】:
我有两个要合并的 csv 文件。
文件1:
rel_id, acc_id, value, timestamp
1, 2, True, 2016-01-04 19:20:22
2, 3, True, 2016-01-04 18:35:56
1, 2, True, 2016-01-04 20:43:12
1, 5, False, 2016-01-04 18:15:20
2, 3, True, 2016-01-04 20:43:11
文件2:
rel_id, acc_id, value, timestamp
1, 2, 250, 2016-01-04 20:43:13
1, 5, 610, 2016-01-04 18:15:23
2, 3, 400, 2016-01-04 18:35:58
2, 3, 300, 2016-01-04 20:43:13
1, 2, 500, 2016-01-04 19:20:23
我想根据 rel_id、acc_id 和时间戳合并这两个文件。
合并(文件 1 和文件 2):
rel_id, acc_id, value_file1, timestamp, value_file2
1, 2, True, 2016-01-04 19:20:22, 500
2, 3, True, 2016-01-04 18:35:56, 400
1, 2, True, 2016-01-04 20:43:12, 250
1, 5, False, 2016-01-04 18:15:20, 610
2, 3, True, 2016-01-04 20:43:11, 300
不过 file2 的时间戳稍晚一些。
在 stackoverflow 上搜索将我带到这篇文章:pandas merge dataframes by closest time
但我不知道如何在 rel_id、acc_id 和最近的时间戳上进行匹配。
import pandas as pd
file1 = pd.read_csv('file1.csv')
file2 = pd.read_csv('file2.csv')
file1.columns = ['rel_id', 'acc_id', 'value', 'timestamp']
file2.columns = ['rel_id', 'acc_id', 'value', 'timestamp']
file1['timestamp'] = pd.to_datetime(file1['timestamp'])
file2['timestamp'] = pd.to_datetime(file2['timestamp'])
file1_dt = pd.Series(file1["timestamp"].values, file1["timestamp"])
file1_dt.reindex(file2["timestamp"], method="nearest")
file2["nearest"] = file1_dt.reindex(file2["timestamp"], method="nearest").values
print file2
我根据另一篇文章尝试了上面的代码,但这与 rel_id 和 acc_id 不匹配。加上上面的代码已经引发了一个错误:
ValueError: index 必须单调递增或递减
非常感谢任何帮助。谢谢。
【问题讨论】:
-
这不是总是选择提前的文件吗?没有多大意义,还是我误解了什么?