【问题标题】:Add new columns based on values in other columns根据其他列中的值添加新列
【发布时间】:2022-12-17 22:18:24
【问题描述】:

我正在努力将以下代码行转换为 r.

for genre in c_a:
    df['is_'+str(genre)] = df['genre'].apply(lambda x: genre in [y.strip() for y in x.split(',')])

基本上,我有一个对象(类型为“字符”,其中有 1341 个值),我想为变量的每个值添加新列,并通过检查是否将 0/1 值分配给新列新栏目包含在流派栏目中。

例如:

当前输入:

Genre
dance pop, pop
country, pop

预期输出:

Genre dance pop pop country
dance pop, pop 1 1 0
country, pop 0 1 1

我对R中的apply和lambda函数不熟悉,只知道通过for循环解决问题,比较慢。

【问题讨论】:

  • 您好,您需要 Python 中的帮助代码吗?如果没有,建议您从标签中删除 python。
  • 您的输入到底是什么样子的?
  • @R。 Baraiya 嗨,我想在 R 中获得帮助。谢谢你提出这个问题。
  • @Martin Gal 你好,我已经编辑了我的问题,所以你可以看到当前的输入和预期的输出。基本上,现在我只有“流派”列和其他功能,我想通过查看它的值来修改这个“流派”。
  • 您的输入是数据框还是向量?

标签: r dataframe function apply


【解决方案1】:

Python:

import pandas as pd

df = pd.DataFrame({"Genre": ["Dance pop, pop", "country, pop"]})
for col in set(sum([i.split(',') for i in df['Genre']],[])):          ##['Dance pop', ' pop', 'country', ' pop']
    df[col] = df['Genre'].apply(lambda x: 1 if col in x.split(',') else 0)
df

【讨论】:

    【解决方案2】:

    您可以使用 tidyverse 方法,但我怀疑它会加快速度。假设你的数据存储在一个向量genre中:

    library(tidyverse)
    
    genre <- c("dance pop, pop", "country, pop")
    
    genre %>% 
      data.frame(genre = .) %>% 
      expand_grid(genres = unique(trimws(unlist(strsplit(genre, ","))))) %>% 
      mutate(value = +str_detect(genre, genres)) %>% 
      pivot_wider(names_from = genres)
    

    这返回

    # A tibble: 2 x 4
      genre          `dance pop`   pop country
      <chr>                <int> <int>   <int>
    1 dance pop, pop           1     1       0
    2 country, pop             0     1       1
    
    • 首先,我们创建一个带有新genres 列的 data.frame,其中包含从 genre 向量中提取的所有独特流派。
    • 接下来我们寻找genresgenre 列之间的匹配项,将其转换为二进制值。
    • 最后我们使用pivot_wider 将其变成矩形。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-16
      • 1970-01-01
      • 2020-10-31
      • 1970-01-01
      • 2015-10-01
      相关资源
      最近更新 更多