【问题标题】:Create a new column in data frame based on the range found in another column and a common column根据在另一列和公共列中找到的范围在数据框中创建一个新列
【发布时间】:2021-12-29 07:42:30
【问题描述】:

我正在尝试根据另一个数据框中的值在数据框中创建一个新列。

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 之间

输出df1,

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

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案1】:

    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
    

    【讨论】:

    • 感谢您的回答,它适用于我的情况。但是,如果我想在这种情况下进行左连接,我也想知道最好的方法是什么。例如,我想保留 df1 中的所有行,即使它在 df2 中没有找到匹配的名称或范围。
    • 只做df1.merge(df2, how='left') 。在这种情况下,df1 成为您的 left df。
    • df1.merge(df2, on ='Name', how='left', indicator=True).query('(_merge == "left_only") | ((Depth >= Start_Depth) & (Depth
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 2021-11-10
    • 2019-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多