【问题标题】:How to swap specific pairs of data across rows in R/Python based on another dataframe如何基于另一个数据框在 R/Python 中的行之间交换特定的数据对
【发布时间】:2021-02-09 03:54:22
【问题描述】:

我想使用 R 或 Python 跨行交换特定数据对的值。我有一个包含逐行试验的第一个数据框,以及第二个数据框,它是试验中出现的单词顺序的参考列表。由于第一个数据帧中的某些单词对的顺序不正确,我想根据第二个数据帧交换不按顺序排列的特定单词对。

第一个数据框如下所示:

SN    word1   word2 

1     dog      cat 

2     mouse    rabbit

3     sheep    goat 

4      ox      snake  

5     cat      dog    

我有第二个数据框,如下所示:

word1   word2

 cat    dog

 mouse  rabbit

 sheep  goat

 snake  ox

我想要做的是在第一个数据帧的行中交换某些值,以便单词按照第二个数据帧指定的顺序。例如,第二个数据帧指定 cat 是“word1”,dog 是“word2”,所以如果第一个数据帧中有一个实例,其中 dog 是“word1”,cat 是“word2”,我想为要切换的单词。

最终的输出应该是这样的:

SN    word1   word2 

1     cat      dog 

2     mouse    rabbit

3     sheep    goat 

4     snake    ox  

5     cat      dog  

有没有办法在 R 或 Python 中实现这一点?任何帮助将不胜感激!

【问题讨论】:

    标签: python r dataframe


    【解决方案1】:

    假设这两个数据帧被称为df1df2,一种方法是按字母顺序对数据帧中的单词进行排序并执行连接。最后将订单保留在df2

    在 R 中,您可以这样做:

    library(dplyr)
    
    df1 %>%
      mutate(sort_col1 = pmin(word1, word2), 
             sort_col2 = pmax(word1, word2)) %>%
      left_join(df2 %>%
                mutate(sort_col1 = pmin(word1, word2), 
                        sort_col2 = pmax(word1, word2)), 
                by = c('sort_col1', 'sort_col2')) %>%
      transmute(SN, word1  = word1.y, word2 = word2.y)
    
    #  SN word1  word2
    #1  1   cat    dog
    #2  2 mouse rabbit
    #3  3 sheep   goat
    #4  4 snake     ox
    #5  5   cat    dog
    

    数据

    df1 <- structure(list(SN = 1:5, word1 = c("dog", "mouse", "sheep", "ox", 
    "cat"), word2 = c("cat", "rabbit", "goat", "snake", "dog")), 
    class = "data.frame", row.names = c(NA, -5L))
    
    df2 <- structure(list(word1 = c("cat", "mouse", "sheep", "snake"),
    word2 = c("dog","rabbit", "goat", "ox")), 
    class = "data.frame", row.names = c(NA, -4L))
    

    【讨论】:

      猜你喜欢
      • 2016-08-18
      • 2020-04-21
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      • 2016-05-07
      • 2021-12-16
      • 1970-01-01
      相关资源
      最近更新 更多