python - 如何基于另一个数据框在 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 中实现这一点?任何帮助将不胜感激!
解决方案
假设调用了两个数据帧df1
和df2
,一种方法是按字母顺序对数据帧中的单词进行排序并执行连接。最后保持订单存在于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))
推荐阅读
- c# - Output.analysis = 等待任务;在视频帧分析示例中返回异常
- google-apps-script - 从谷歌应用脚本更新谷歌电子表格时,我收到错误消息“您无权访问请求的文档。”
- xml - 如何修复 XSLT 中一个元素中的 XPTY0004 错误 2 项从 XML 到 XML
- json - 为什么json第二次加载json_file失败
- python - 根据 Pandas 中的其他列添加列并填充缺失值
- c# - 如何从 CellClick 事件中获取行?
- teradata - 需要对 teradata SQL Query 中的数据进行加密
- python - 如何在 Python 中启动一个独立运行的子进程,并在主进程关闭时继续运行?
- node.js - 我的 Node Express 应用程序发出这些 GET 请求?
- html - 如何在 Bootstrap 4 中的图像覆盖卡上垂直对齐?