[英]How to add a column in one long dataframe based on a match and range values in another wide dataframe?
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.我想将“名称”列添加到 df2,其中值由匹配 df1 中的“id”以及 df2 中的“T”值是否介于 df1 中的“Tin”和“Tout”之间。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.