![](/img/trans.png)
[英]Compare timestamps in two different DataFrames with different length and then merge them
[英]Merge two dataframes with different timestamps
我有两个数据框:
df1 =
时间 | 一种 | 乙 | C |
---|---|---|---|
19:43:58:428 | 10 | 2个 | 3个 |
19:44:07:777 | 5个 | 1.5 | -2 |
df2 =
时间 | 丁 | 乙 |
---|---|---|
19:43:58:372 | 2.154 | 3.5 |
19:43:58:872 | 3.14 | 1.3 |
19:44:07:372 | 1.4 | 2个 |
19:44:07:872 | 1.76 | 2.2 |
19:44:07:910 | 1.43 | 2.43 |
我必须合并这些数据帧,使 df2 的时间最接近 df1 的时间。 所以得到的 df 将是:
df_result =
时间 | 一种 | 乙 | C | 丁 | 乙 |
---|---|---|---|---|---|
19:43:58:428 | 10 | 2个 | 3个 | 2.154 | 3.5 |
19:44:07:777 | 5个 | 1.5 | -2 | 1.76 | 2.2 |
如何使用 pandas 做到这一点?
您可以使用pandas.merge_asof
,传递nearest
的方向参数,它会根据最小的差异进行合并。
df1['Time'] = pd.to_datetime(df1['Time'], format='%H:%M:%S:%f')
df2['Time'] = pd.to_datetime(df2['Time'], format='%H:%M:%S:%f')
pd.merge_asof(df1, df2, on='Time', direction='nearest')
OUTPUT:
Time A B C D E
0 1900-01-01 19:43:58.428 10 2.0 3 2.154 3.5
1 1900-01-01 19:44:07.777 5 1.5 -2 1.760 2.2
您可以使用strftime('%H:%M:%S:%f')
将时间列转换回以前的格式
PS: merge_asof
要求dataframe中的key进行排序,你可能希望在合并前对key进行排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.