[英]Python Pandas — mapping the values in two data frames
I have two dataframes df1
and df2
. 我有两个数据
df1
和df2
。
I am trying to figure out the best way to perform a mapping that for each row in df1
, I would like to search for a match ( id
, time_by_hour
) in df2
and then fill the corresponding value in df2
back into df1
. 我试图找出执行映射的最佳方法,即对于
df1
中的每一行,我想在df2
搜索匹配项( id
, time_by_hour
),然后将df2
的相应值填回到df1
。
Below is the df1_final
as I would like it to look finally. 下面是
df1_final
,我希望它最终看起来是。
Thank you in advance! 先感谢您!
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
你可以看一下merge
df1['value']=df1[['time_by_hour','id']].merge(df2,how='left').value
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.