Python Pandas - 将值映射到两个数据帧中

时间:2018-03-20 17:45:54

标签: python pandas merge mapping vectorization

我有两个数据框df1df2

我正在尝试找出执行df1中每一行的映射的最佳方法,我想在{idtime_by_hour中搜索匹配项df2df2) {1}}然后将df1中的相应值填回df1_final

以下是df1 Out[100]: id time_by_min time_by_hour value 0 a 2017-06-30 01:25:00.000 2017-06-30 02:00:00 NaN 1 a 2017-06-30 01:36:32.308 2017-06-30 02:00:00 NaN 2 a 2017-06-30 02:25:00.000 2017-06-30 03:00:00 NaN 3 a 2017-06-30 02:36:32.308 2017-06-30 03:00:00 NaN 4 b 2017-06-30 01:25:00.000 2017-06-30 02:00:00 NaN 5 b 2017-06-30 01:36:32.308 2017-06-30 02:00:00 NaN 6 b 2017-06-30 02:25:00.000 2017-06-30 03:00:00 NaN df2 Out[101]: id time_by_hour value 0 a 2017-06-30 02:00:00 100 1 a 2017-06-30 03:00:00 200 2 b 2017-06-30 02:00:00 150 3 b 2017-06-30 03:00:00 30 4 c 2017-06-30 02:00:00 80 5 c 2017-06-30 03:00:00 900 df1_final Out[102]: id time_by_min time_by_hour value 0 a 2017-06-30 01:25:00.000 2017-06-30 02:00:00 100 1 a 2017-06-30 01:36:32.308 2017-06-30 02:00:00 100 2 a 2017-06-30 02:25:00.000 2017-06-30 03:00:00 200 3 a 2017-06-30 02:36:32.308 2017-06-30 03:00:00 200 4 b 2017-06-30 01:25:00.000 2017-06-30 02:00:00 150 5 b 2017-06-30 01:36:32.308 2017-06-30 02:00:00 150 6 b 2017-06-30 02:25:00.000 2017-06-30 03:00:00 30 ,我希望最终看到它。

提前谢谢!

{{1}}

1 个答案:

答案 0 :(得分:2)

您可以查看merge

df1['value']=df1[['time_by_hour','id']].merge(df2,how='left').value