繁体   English   中英

Python 到 R 翻译

[英]Python to R Translation

我在 Python 中有几行代码,我试图在 R 中复制它们,但我承认我目前还不够熟练,无法弄清楚。

这是 Python 中的代码:

import pandas as pd
df = pd.DataGram ({'col_a' : ["blue shovel 1024", "red shovel 1022", "green bucket 3021", "green rake 3021", 
"yellow shovel 1023"], 'col_b' : ["blue", "red", "green", "blue", "yellow"]},

columns = ["col_a", "col_b"])

unique_words = list(df.col_b.unique())
unique
["blue", "red", "green", "yellow"]

df['result] = df['col_a'].apply(lambda x:','.join([item for item in str(x).split () \
                                                  if item in unique_words]))

运行上述代码的结果为您提供:

    col_a                      col_b          result
1   blue shovel 1024           blue           blue
2   red shovel 1022            red            red
3   green buckets 3021         green          green
4   green rake 3021            blue           green
5   yellow shovel 1023         yellow         yellow

这段代码的目标是在 col_b 中创建一个唯一值列表,然后在 col_a 中搜索这些唯一值中的任何一个,如果找到它们,将它们放在结果列中。 请注意,在第 4 行中,结果为绿色。 这是正确的,因为即使 col_b 显示第 4 行的值是蓝色的,col_a 中的实际值也是绿色的。

我试过重写这个部分:

df['result] = df['col_a'].apply(lambda x:','.join([item for item in str(x).split () \
                                                  if item in unique_words]))

在 R 中(我的想法是写一个 function 并尝试一个 lapply(),但要么我做错了,要么这不是正确的方法。提前谢谢你的任何建议或帮助,我会回来看看如果有任何问题我可以回答或信息我可以帮助澄清。再次感谢您!

library(tidyverse)

df <- tibble(
  col_a = c("blue shovel 1024", "red shovel 1022", "green bucket 3021", "green rake 3021", "yellow shovel 1023"),
  col_b = c("blue", "red", "green", "blue", "yellow")
)
df
#> # A tibble: 5 x 2
#>   col_a              col_b 
#>   <chr>              <chr> 
#> 1 blue shovel 1024   blue  
#> 2 red shovel 1022    red   
#> 3 green bucket 3021  green 
#> 4 green rake 3021    blue  
#> 5 yellow shovel 1023 yellow

unique_words <- unique(df$col_b)
unique_words
#> [1] "blue"   "red"    "green"  "yellow"
unique_words_regex <- unique_words %>% paste0(collapse = "|")

df <- mutate(df, result = col_a %>% str_extract(unique_words_regex))
df
#> # A tibble: 5 x 3
#>   col_a              col_b  result
#>   <chr>              <chr>  <chr> 
#> 1 blue shovel 1024   blue   blue  
#> 2 red shovel 1022    red    red   
#> 3 green bucket 3021  green  green 
#> 4 green rake 3021    blue   green 
#> 5 yellow shovel 1023 yellow yellow

代表 package (v2.0.1) 于 2021 年 12 月 15 日创建

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM