繁体   English   中英

根据在另一列和公共列中找到的范围在数据框中创建一个新列

[英]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 列,基于两个条件,

  1. “名称”应在两个数据框中匹配
  2. 对于相同的“名称”,df1.Depth 应该在 df2 中的 Start_Depth 和 End_Depth 之间

Output df1,

Name    Depth   Zone
A   100 Zone1
A   120 Zone1
B   200 Zone4

df.mergedf.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM