[英]Python Pandas — mapping the values in two data frames
我有兩個數據df1
和df2
。
我試圖找出執行映射的最佳方法,即對於df1
中的每一行,我想在df2
搜索匹配項( id
, time_by_hour
),然后將df2
的相應值填回到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
你可以看一下merge
df1['value']=df1[['time_by_hour','id']].merge(df2,how='left').value
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.