【发布时间】:2016-08-05 19:01:20
【问题描述】:
我想在 R 或 Python 中合并两个表,每个表都有数万行。但是,我将无法合并完美匹配。我正在寻找一个键是另一个键的子字符串的情况。匹配的子字符串可以包含多个单词。 我正在寻找比下面的蛮力代码更快的解决方案。
https://stackoverflow.com/users/170352/brandon-bertelsen 给出了一个很好的答案,基于我最初建议的玩具数据。但是,它只匹配单个单词的子字符串。 (我最初并没有明确提出这个要求。)
这是我将用于这种情况的代码。
library(SPARQL)
library(parallel)
library(Hmisc)
library(tidyr)
library(dplyr)
my.endpoint <- "http://sparql.hegroup.org/sparql/"
go.query <- 'select *
where { graph <http://purl.obolibrary.org/obo/merged/GO>
{ ?goid
<http://www.geneontology.org/formats/oboInOwl#hasOBONamespace>
"biological_process"^^<http://www.w3.org/2001/XMLSchema#string> .
?goid rdfs:label ?goterm}}'
go.result <- SPARQL(url = my.endpoint, query = go.query)
go.result.frame <- go.result[[1]]
anat.query <- 'select distinct ?anatterm ?anatid
where { graph <http://purl.obolibrary.org/obo/merged/UBERON>
{ ?anatid <http://www.geneontology.org/formats/oboInOwl#hasDbXref> ?xr .
?anatid rdfs:label ?anatterm}}'
anat.result <- SPARQL(url = my.endpoint, query = anat.query)
anat.result.frame <- anat.result[[1]]
# slow but recognizes multi-word substrings
loop.solution <-
mclapply(
X = sort(anat.result.frame$anatid),
mc.cores = 7,
FUN = function(one.anat.id) {
one.anat.term <-
anat.result.frame$anatterm[anat.result.frame$anatid == one.anat.id]
temp <-
grepl(pattern = paste0('\\b', one.anat.term, '\\b'),
x = go.result.frame$goterm)
temp <- go.result.frame[temp , ]
if (nrow(temp) > 0) {
temp$anatterm <- one.anat.term
temp$anatid <- one.anat.id
return(temp)
}
}
)
loop.solution <- do.call(rbind, loop.solution)
# from Brandon
# fast, but doesn't recognize multi-word matches
sep.gather.soln <-
separate(go.result.frame,
goterm,
letters,
sep = " ",
remove = FALSE) %>%
gather(goid, goterm) %>%
na.omit() %>%
setNames(c("goid", "goterm", "code", "anatterm")) %>%
select(goid, goterm, anatterm) %>%
left_join(anat.result.frame) %>%
na.omit()
【问题讨论】:
-
set( term +' '+ cat for term in terms for cat in set([ dictionary .get(word,'') for word in term.split()]) if cat)跨度>
-
谢谢。我无法确定此代码中的换行符和缩进的位置。
-
这是一行代码
-
请使用真实数据更新您的示例。我不打算安装所有这些软件包,所以只关注我需要解决您遇到的问题的最后一部分所需的数据。显示非常清晰的示例输入和输出。
标签: python r string optimization