Lut*_*ett 2 python r dataframe pandas dplyr
我有一个操作需要将R 中的dplyr
(and ) 转换为python 中的操作。在 R 中它非常简单,但我还无法在 pandas 中理解它。基本上,我需要按一(或多)列进行分组,然后将剩余的列连接在一起并用分隔符折叠它们。R 有一个很好的向量化函数,它完全可以满足我的需求。stringr
pandas
str_c
这是 R 代码:
\nlibrary(tidyverse)\ndf <- as_tibble(structure(list(file = c(1, 1, 1, 2, 2, 2), marker = c("coi", "12s", "16s", "coi", "12s", "16s"), start = c(1, 22, 99, 12, 212, 199), end = c(15, 35, 102, 150, 350, 1102)), row.names = c(NA, -6L), class = "data.frame") )\n\ndf %>%\n group_by(file) %>%\n summarise(markers = str_c(marker,"[",start,":",end,"]",collapse="|"))\n#> # A tibble: 2 \xc3\x97 2\n#> file markers \n#> <dbl> <chr> \n#> 1 1 coi[1:15]|12s[22:35]|16s[99:102] \n#> 2 2 coi[12:150]|12s[212:350]|16s[199:1102]\n
Run Code Online (Sandbox Code Playgroud)\n这是 python 代码的开头。agg
我认为or有一些技巧,transform
但我不确定如何组合和连接多个列:
library(tidyverse)\ndf <- as_tibble(structure(list(file = c(1, 1, 1, 2, 2, 2), marker = c("coi", "12s", "16s", "coi", "12s", "16s"), start = c(1, 22, 99, 12, 212, 199), end = c(15, 35, 102, 150, 350, 1102)), row.names = c(NA, -6L), class = "data.frame") )\n\ndf %>%\n group_by(file) %>%\n summarise(markers = str_c(marker,"[",start,":",end,"]",collapse="|"))\n#> # A tibble: 2 \xc3\x97 2\n#> file markers \n#> <dbl> <chr> \n#> 1 1 coi[1:15]|12s[22:35]|16s[99:102] \n#> 2 2 coi[12:150]|12s[212:350]|16s[199:1102]\n
Run Code Online (Sandbox Code Playgroud)\n
(df.astype(str)
.assign(markers = lambda df: df.marker + "[" + (df.start + ":"+df.end) + "]")
.groupby('file', as_index=False)
.markers
.agg("|".join)
)
file markers
0 1.f coi[1:15]|12s[22:35]|16s[99:102]
1 2.f coi[12:150]|12s[212:350]|16s[199:1102]
Run Code Online (Sandbox Code Playgroud)
这个想法是先组合列,然后再使用 python 的 str.join 方法进行分组和聚合
归档时间: |
|
查看次数: |
728 次 |
最近记录: |