我有一個資料框 (df1) 并希望從另一個資料框 (df2) 中獲取 ID 和相關分數的先前最新調查日期
df1 = pd.DataFrame({'ID' : [1,2],
'start_date':['2018-08-04','2018-08-09']})
df1
df2 = pd.DataFrame({'ID' : [1,1,2,2],
'survey_date':['2018-08-01','2018-08-05','2018-08-08','2018-08-10'],
'score':[200,100, 400, 800]})
df2
期望的輸出
| ID | 開始日期 | prev_survey_date | 分數 |
|---|---|---|---|
| 1 | 2018-08-04 | 2018-08-01 | 200 |
| 2 | 2018-08-09 | 2018-08-08 | 400 |
我怎樣才能在python中做到這一點?
uj5u.com熱心網友回復:
你可以試試merge_asof
#df1.start_date = pd.to_datetime(df1.start_date)
#df2.survey_date = pd.to_datetime(df2.survey_date)
out = pd.merge_asof(df1, df2, by = 'ID', left_on = 'start_date', right_on = 'survey_date')
Out[366]:
ID start_date survey_date score
0 1 2018-08-04 2018-08-01 200
1 2 2018-08-09 2018-08-08 400
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/492082.html
