代码之家  ›  专栏  ›  技术社区  ›  Mohamed Thasin ah

如何匹配和替换两个数据帧之间的元素

  •  4
  • Mohamed Thasin ah  · 技术社区  · 6 年前

    我需要将一个数据帧值中的元素替换为另一个数据帧。

    例如:

    DF1:

       id  value
    0   1     10
    1   2     12
    2   3     54
    3   4     21
    

    DF2:

       col1  col2  col3
    0     1     2     3
    1     1     1     3
    2     1     3     4
    3     1     1     5
    

    预期输出:

    替换的值来自 df1 并应用于 df2 .

       col1  col2  col3
    0    10    12    54
    1    10    10    54
    2    10    54    21
    3    10    10     5
    

    如何做到这是在R?

    我会像下面这样在熊猫身上解决这个问题,

    dic=df1.set_index('id')['value'].to_dict()
    print df2.replace(dic)
    

    但我被困在R。

    请帮我解决这个问题?

    3 回复  |  直到 6 年前
        1
  •  3
  •   Ronak Shah    6 年前

    我们可以循环遍历 df2 使用 lapply 找到一个 match 对于 id df1 并使用替换找到的匹配项的值 ifelse 保持剩余值不变。

    df2[] <- lapply(df2, function(x) {
       inds <- match(x, df1$id)
       ifelse(is.na(inds),x, df1$value[inds]) 
    })
    
    
    df2
    
    #  col1 col2 col3
    #0   10   12   54
    #1   10   10   54
    #2   10   54   21
    #3   10   10    5
    
        2
  •  2
  •   akrun    6 年前

    我们可以在创建第二个数据集的副本之后使用命名向量来完成这项工作。

    df3 <- df2
    df3[] <- setNames(df1$value, df1$id)[as.matrix(df2)]
    i1 <- is.na(df3)
    df3[i1] <- df2[i1] 
    df3
    #  col1 col2 col3
    #0   10   12   54
    #1   10   10   54
    #2   10   54   21
    #3   10   10    5
    
        3
  •  2
  •   Onyambu    6 年前

    你能做的:

    复制DF2:

    df3=df2 # in R this is  a copy not as in python
    df3[]=df1$value[match(as.matrix(df2),df1$id)] # Match the columns
    df3[is.na(df3)]=df2[is.na(df3)] # Reset Na to the previous value
    df3
      col1 col2 col3
    0   10   12   54
    1   10   10   54
    2   10   54   21
    3   10   10    5