python - 使用 R 或 Python 将数据框列中的字符串与另一个数据框列中的字符串匹配

标签 python r string string-matching

我正在尝试将数据框列中的字符串与另一个数据框列中的字符串进行匹配,并映射相应的值。两个数据框的行数不同

df1 = data.frame(name = c("(CKMB)Creatinine Kinase Muscle & Brain", "24 Hours Urine for Sodium", "Antistreptolysin O Titer", "Blood group O", lonic_code = c("27816-8-O", "27816-8-B", "1869-7", "33914-3")
df2 = data.frame(Testcomponents = c("creatinine", "blood", "potassium"))

预期输出

Test Components          lonic_code
creatinine                27816-8-O
 blood                      1869-7
potassium                    NA

最佳答案

regex_right_join 在这种情况下会很方便。

library(fuzzyjoin)
library(dplyr)

df1 %>%
  mutate(name = as.character(name)) %>%
  regex_right_join(df2 %>%
                     mutate(Testcomponents = as.character(Testcomponents)), 
                   by = c(name = "Testcomponents"), ignore_case = T) %>%
  select(Testcomponents, lonic_code)

输出是:

  Testcomponents lonic_code
1     creatinine  27816-8-O
2          blood    33914-3
3      potassium       <NA>

示例数据:

df1 <- structure(list(name = structure(1:4, .Label = c("(CKMB)Creatinine Kinase Muscle & Brain", 
"24 Hours Urine for Sodium", "Antistreptolysin O Titer", "Blood group O"
), class = "factor"), lonic_code = structure(c(3L, 2L, 1L, 4L
), .Label = c("1869-7", "27816-8-B", "27816-8-O", "33914-3"), class = "factor")), .Names = c("name", 
"lonic_code"), row.names = c(NA, -4L), class = "data.frame")

df2 <- structure(list(Testcomponents = structure(c(2L, 1L, 3L), .Label = c("blood", 
"creatinine", "potassium"), class = "factor")), .Names = "Testcomponents", row.names = c(NA, 
-3L), class = "data.frame")

关于python - 使用 R 或 Python 将数据框列中的字符串与另一个数据框列中的字符串匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48536058/

相关文章:

python - 字典内的字符串格式?

Python:在现有列中创建分类变量

c# - 如何访问用户控件的项目

java - 这种模式的正则表达式是什么?

python - 通过 gspread 和 Google Sheets API 更改 Google Sheets 中的列格式

python:从html获取图像链接

r - 间隔 R 内的周末日期

r - extract_function(initial_response)中的错误:R中的elasticsearchr中没有返回查询结果

r - 有没有通用的方法来引用公式对象中 R 数据框的最后一列?

java - 如何让我的程序识别给定字符串中的字符串和整数?