[英]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.