gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:57:01 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com