[英]Create a new column in data frame based on the range found in another column and a common column
我正在嘗試根據另一個數據框中的值在數據框中創建一個新列。
df1 是,
Name Depth
A 100
A 120
B 200
df2 是,
Name Start_Depth End_Depth Zone
A 50 150 Zone1
A 150 200 Zone2
B 50 120 Zone3
B 120 300 Zone4
我想在 df1 中添加 Zone 列,基於兩個條件,
Output df1,
Name Depth Zone
A 100 Zone1
A 120 Zone1
B 200 Zone4
將df.merge
與df.query
一起使用:
In [120]: r = df1.merge(df2).query('End_Depth >= Depth > Start_Depth')[['Name', 'Depth', 'Zone']]
In [121]: r
Out[121]:
Name Depth Zone
0 A 100 Zone1
2 A 120 Zone1
5 B 200 Zone4
或使用Series.between
:
In [114]: x = df1.merge(df2)
In [124]: r = x[x.Depth.between(x.Start_Depth, x.End_Depth)][['Name', 'Depth', 'Zone']]
In [125]: r
Out[125]:
Name Depth Zone
0 A 100 Zone1
2 A 120 Zone1
5 B 200 Zone4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.