【问题标题】:Double Condition Merge using Pandas使用 Pandas 进行双重条件合并
【发布时间】:2021-02-09 15:44:46
【问题描述】:

我正在尝试使用 python 中的pandas 库合并下表。我尝试使用merge_as_ofmerge 的变体来做到这一点,但没有成功。

主数据:

Asset ID Size (mm) Depth (m)
1 100 1.5
2 400 1
3 500 4.5

条件表:

< Size (mm) < Depth (m) Estimated Repair Time (days)
300 2 1
300 4 1.5
300 6 2
600 2 1.5
600 4 2
600 6 3

实现如下表:

Asset ID Size (mm) Depth (m) Estimated Repair Time
1 100 1.5 1
2 400 1 1.5
3 400 4.5 3

【问题讨论】:

    标签: python pandas merge


    【解决方案1】:

    使用pd.cut 生成大小和深度的范围标签。

    然后用范围标签连接两个表。

    # create label with pd.cut
    # Index(['< Size (mm)', '< Depth (m)', 'Estimated Repair Time (days)'], dtype='object')
    dfa['Size'] = pd.cut(dfa['< Size (mm)'], bins = [0, 300, 600])
    dfa['Depth'] = pd.cut(dfa['< Depth (m)'], bins = [0, 2, 4, 6])
    
    dfm['Size'] = pd.cut(dfm['Size (mm)'], bins = [0, 300, 600])
    dfm['Depth'] = pd.cut(dfm['Depth (m)'], bins = [0, 2, 4, 6])
    
    df = dfm.join(dfa.set_index(['Size', 'Depth'])['Estimated Repair Time (days)'],
             on=['Size', 'Depth'])
    print(df)
    
           Asset ID  Size (mm)  Depth (m)        Size   Depth  \
        0         1        100        1.5    (0, 300]  (0, 2]   
        1         2        400        1.0  (300, 600]  (0, 2]   
        2         3        500        4.5  (300, 600]  (4, 6]   
    
           Estimated Repair Time (days)  
        0                           1.0  
        1                           1.5  
        2                           3.0
    

    【讨论】:

      【解决方案2】:

      你总是可以像关系引擎那样做

      1. 做笛卡尔积
      2. 应用过滤条件
      3. 选择唯一的
      dfm = pd.read_csv(io.StringIO("""Asset ID   Size (mm)   Depth (m)
      1   100 1.5
      2   400 1
      3   500 4.5
      """),sep="\t")
      
      dfa = pd.read_csv(io.StringIO("""< Size (mm)    < Depth (m) Estimated Repair Time (days)
      300 2   1
      300 4   1.5
      300 6   2
      600 2   1.5
      600 4   2
      600 6   3
      """), sep="\t")
      
      dfraw = dfm.assign(foo=1).merge(dfa.assign(foo=1), on="foo", how="left")
      dffinal = (dfraw.loc[dfraw["Size (mm)"].lt(dfraw["< Size (mm)"]) & dfraw["Depth (m)"].lt(dfraw["< Depth (m)"])]
       .groupby("Asset ID", as_index=False).first()
      )
      
      
      Asset ID Size (mm) Depth (m) foo < Size (mm) < Depth (m) Estimated Repair Time (days)
      0 1 100 1.5 1 300 2 1
      1 2 400 1 1 600 2 1.5
      2 3 500 4.5 1 600 6 3

      【讨论】:

        猜你喜欢
        • 2013-12-02
        • 1970-01-01
        • 2019-10-22
        • 2018-02-02
        • 1970-01-01
        • 2021-12-23
        • 2019-10-07
        • 2023-03-23
        • 2021-10-24
        相关资源
        最近更新 更多