【问题标题】:Concatenate the columns of a dataframe (with string values) in python-like paste0 function in R [duplicate]在R中的类似python的paste0函数中连接数据框的列(带有字符串值)[重复]
【发布时间】:2021-12-30 10:27:41
【问题描述】:

下面是输入数据

Type   Cat       Var         Dist    Count
@joy   A1 + B1  x + y + z   0:25:75    4
.cet   C1 + D1  p + q       50:50      2
sam    E1 + F1  g           100:3:2    10

下面是预期的输出

Type   Cat       Var         Dist    Count   Output
@joy   A1 + B1  x + y + z   0:25:75    4    @joyA1 + B1x + y +z
.cet   C1 + D1  p + q       50:50      2    .cetC1 + D1p + q
sam    E1 + F1  g           100:3:2    10    samE1 + F1g

以下是我的尝试:

df.iloc[:,0:3].dot(['Type','Cat','Var'])

【问题讨论】:

    标签: python r pandas string dataframe


    【解决方案1】:

    你可以这样做

    df['output'] = df['Type'].map(str) + df['Cat'].map(str) + df['Var].map(str)
    

    【讨论】:

      【解决方案2】:

      你可以简单地使用:

      df['Output']=df['Type']+' '+df['Cat']+' '+df['Var']
      

      输出:

         Type      Cat        Var         Dist  Count                  output
      0  @joy  A1 + B1  x + y + z  0.018229167      4  @joy A1 + B1 x + y + z
      1  .cet  C1 + D1      p + q     50:50:00      2      .cet C1 + D1 p + q
      2   sam  E1 + F1          g    100:03:02     10           sam E1 + F1 g
      

      【讨论】:

        【解决方案3】:

        基础R:使用paste0

        df$Output <- paste0(df$Type, df$Cat, df$Var)
        
          Type     Cat       Var    Dist Count                 Output
        1 @joy A1 + B1 x + y + z 0:25:75     4 @joy A1 + B1 x + y + z
        2 .cet C1 + D1     p + q   50:50     2     .cet C1 + D1 p + q
        3  sam E1 + F1         g 100:3:2    10          sam E1 + F1 g
        

        library(dplyr)
        df %>% 
          mutate(Output = paste(Type, Cat, Var, sep = ""))
        
          Type     Cat       Var    Dist Count                 Output
        1 @joy A1 + B1 x + y + z 0:25:75     4 @joy A1 + B1 x + y + z
        2 .cet C1 + D1     p + q   50:50     2     .cet C1 + D1 p + q
        3  sam E1 + F1         g 100:3:2    10          sam E1 + F1 g
        

        或者:

        library(tidyr)
        df %>% 
          unite(Output, c(Type, Cat, Var), remove=FALSE)
        
                          Output Type     Cat       Var    Dist Count
        1 @joy_A1 + B1_x + y + z @joy A1 + B1 x + y + z 0:25:75     4
        2     .cet_C1 + D1_p + q .cet C1 + D1     p + q   50:50     2
        3          sam_E1 + F1_g  sam E1 + F1         g 100:3:2    10
        

        【讨论】:

          猜你喜欢
          • 2018-11-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-09-25
          • 1970-01-01
          相关资源
          最近更新 更多