df1 = pd.DataFrame(
{'id': ['5AB', '5AB', '5AB', '5AB', '4CA', '01D', '01D', '4CA'],
'Tin': [9.175, 0.792, 25.674999, 26.806999, 9.75, 7.51, 25.195, 21.316],
'Tout': [20.792, 25.674999, 26.806999, 31.549, 21.316, 19.121, 28.669001, 26.337999],
'name': ['FILIN', 'FILOUT', 'SEIN', 'SEOUT', 'FILIN', 'FIN', 'SEOUT', 'FILOUT']
})
id Tin Tout name
5AB 9.175 20.792 FILIN
5AB 20.792 25.674999 FILOUT
5AB 25.674999 26.806999 SEIN
5AB 26.806999 31.549 SEOUT
4CA 9.75 21.316 FILIN
01D 7.51 19.121 FIN
01D 25.195 28.669001 SEOUT
4CA 21.316 26.337999 FILOUT
df2 = pd.DataFrame(
{'id': ['01D', '01D', '4CA', '4CA', '5AB', '5AB'],
'T': [12.3, 27.5, 22.64, 23.2, 11.52, 2.34],
'Type': ['Temp', 'Pres', 'Prox', 'Prox', 'Pres', 'Axe'],
'val': [11.3, 1, 0, 2, 0.5, 23.1]
})
id T Type Val
01D 12.3 Temp 11.3
01D 27.5 Pres 1
4CA 22.64 Proximity 0
4CA 23.2 Proximity 2
5AB 11.52 Pres 0.5
5AB 2.34 Axe 23.1
I want to add the 'name' column to df2 where the value is dictated by matching 'id' in df1 and also whether the 'T' value in df2 is between 'Tin' and 'Tout' in df1. If there is no applicable range then set 'name' as None.
I am trying to get the following outcome:
id T Type Val name
01D 12.3 Temp 11.3 FIN
01D 27.5 Pres 1 SEOUT
4CA 22.64 Proximity 0 FILOUT
4CA 23.2 Proximity 2 FILOUT
5AB 11.52 Pres 0.5 FILIN
5AB 2.34 Axe 23.1 None
I can usually search my way out of these situations but not this time. Appreciate your help!
here is one way to do it
df2.merge(df1, on='id').query('T >= Tin & T<=Tout').drop(columns=['Tin', 'Tout'])
id T Type val name
0 01D 12.30 Temp 11.3 FIN
3 01D 27.50 Pres 1.0 SEOUT
5 4CA 22.64 Prox 0.0 FILOUT
7 4CA 23.20 Prox 2.0 FILOUT
8 5AB 11.52 Pres 0.5 FILIN
9 5AB 11.52 Pres 0.5 FILOUT
13 5AB 2.34 Axe 23.1 FILOUT
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.