首页 > 解决方案 > 如何基于另一个数据框在 R/Python 中的行之间交换特定的数据对

问题描述

我想使用 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 中实现这一点?任何帮助将不胜感激!

标签: pythonrdataframe

解决方案


假设调用了两个数据帧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))

推荐阅读