I have a dataframe named calls, each call is recorded by a date (calls)[datetime]. each call has an answer status (calls)[Status].
JavaScript
x
5
1
a = {'datetime':['2021-11-22 18:47:02','2021-01-08 14:18:11','2021-06-08 16:40:45','2021-12-03 10:21:31','2021-12-03 15:21:31'],
2
'Status': ['P_TR_SOK', 'RS_GEN', 'P_TR_ST_','RS_GEN', 'MLR_ST']}
3
4
calls = pd.DataFrame(data = a)
5
A second Dataframe named NewStatus with same column (NewStatus
)[datetime] and the column (NewStatus
)[New_Status] that I want to replace in the first dataframe with a date join
JavaScript
1
5
1
b = {'datetime': ['2021-11-22 18:47:02','2021-01-08 14:18:11','2021-06-08 16:40:45','2021-12-03 10:21:31'],
2
'New_Status': ['AB_CL_NO','REP','AB_AUT','DROP']}
3
4
NewStatus = pd.DataFrame(data = b)
5
Desired result is the following for calls :
datetime | Status |
---|---|
2021-11-22 18:47:02 | AB_CL_NO |
2021-01-08 14:18:11 | REP |
2021-06-08 16:40:45 | AB_AUT |
2021-12-03 10:21:31 | DROP |
2021-12-03 15:21:31 | MLR_ST |
By using
JavaScript
1
2
1
calls.reset_index().set_index('datetime').join(NewStatus.drop_duplicates().set_index('datetime'), how='left', rsuffix='df2')
2
I am blocked how to replace the old Status by making the join with “datetime”
Advertisement
Answer
You could do it like this:
UPDATE
Be aware that pd.update
works inplace
.
JavaScript
1
12
12
1
calls= calls.set_index('datetime')
2
calls.update(NewStatus.set_index('datetime').rename(columns={'New_Status': 'Status'}))
3
print(calls)
4
5
Status
6
datetime
7
2021-11-22 18:47:02 AB_CL_NO
8
2021-01-08 14:18:11 REP
9
2021-06-08 16:40:45 AB_AUT
10
2021-12-03 10:21:31 DROP
11
2021-12-03 15:21:31 MLR_ST
12
Old answer
JavaScript
1
16
16
1
calls= calls.set_index('datetime')
2
out = (calls.join(NewStatus.drop_duplicates()
3
.set_index('datetime')
4
.rename(columns={'New_Status':'Status'}), how='left', rsuffix='_updated')
5
.rename(columns={'Status_updated': 'Replaced_Status'})
6
.drop('Status', axis=1)
7
.dropna())
8
print(out)
9
10
Replaced_Status
11
datetime
12
2021-11-22 18:47:02 AB_CL_NO
13
2021-01-08 14:18:11 REP
14
2021-06-08 16:40:45 AB_AUT
15
2021-12-03 10:21:31 DROP
16