【问题标题】:How to concatenate all (string) values in a given pandas dataframe row to one string?如何将给定熊猫数据框行中的所有(字符串)值连接到一个字符串?
【发布时间】:2017-11-24 02:29:28
【问题描述】:

我有一个看起来像这样的 pandas 数据框:

     0        1            2        3       4
0    I        want         to       join    strings  
1    But      only         in       row     1

所需的输出应如下所示:

     0        1      2        3       4       5
1    But      only   in       row     1       I want to join strings

如何将这些字符串连接成一个联合字符串?

【问题讨论】:

    标签: python string pandas


    【解决方案1】:

    IIUC,通过使用applyjoin

    df.apply(lambda x :' '.join(x.astype(str)),1)
    Out[348]: 
    0    I want to join strings
    1         But only in row 1
    dtype: object
    

    然后你可以分配它们

    df1=df.iloc[1:]
    df1['5']=df.apply(lambda x :' '.join(x.astype(str)),1)[0]
    df1
    Out[361]: 
         0     1   2    3  4                       5
    1  But  only  in  row  1  I want to join strings
    

    时间安排:

    %timeit df.apply(lambda x : x.str.cat(),1)
    1 loop, best of 3: 759 ms per loop
    %timeit df.apply(lambda x : ''.join(x),1)
    1 loop, best of 3: 376 ms per loop
    
    
    df.shape
    Out[381]: (3000, 2000)
    

    【讨论】:

      【解决方案2】:

      使用str.cat 加入第一行,并分配给第二行。

      i = df.iloc[1:].copy()   # the copy is needed to prevent chained assignment
      i[df.shape[1]] = df.iloc[0].str.cat(sep=' ')
      
      i     
           0     1   2    3  4                       5
      1  But  only  in  row  1  I want to join strings
      

      【讨论】:

      • 我需要再次检查pandas API..哈哈:-)
      【解决方案3】:

      另一种替代方法是使用add 空格,后跟sum

      df[5] = df.add(' ').sum(axis=1).shift(1)

      结果:

           0     1   2     3        4                       5
      0    I  want  to  join  strings                     NaN
      1  But  only  in   row        1  I want to join strings 
      

      【讨论】:

        【解决方案4】:

        如果您的数据集不够完美,并且您想排除 'nan' 值,您可以使用这个:

        df.apply(lambda x :' '.join(x for x in x.astype(str) if x != "nan"),1)
        

        我发现这在将包含部分地址的列连接在一起时特别有用,其中某些部分(例如 SubLocation)(例如公寓#)与所有地址都不相关。

        【讨论】:

          猜你喜欢
          • 2017-02-24
          • 1970-01-01
          • 2018-09-24
          • 1970-01-01
          • 2013-07-09
          • 2017-07-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多