【问题标题】:Pandas merging selected columns into 1熊猫将选定的列合并为 1
【发布时间】:2018-07-09 23:44:22
【问题描述】:

我有一个这样的 df:

ID1 ID2 Day Text1 Text2 Text3 ....
111 A   1   a     b     c
222 B   2   i     j     k
333 C   3   x     y     z

我的目标是创建一个包含 Text1、Text2、Text3 等所有值的新列。

ID1 ID2 Day Text1 Text2 Text3 ....  Text
111 A   1   a     b     c           a, b, c...
222 B   2                          
333 C   3   x           y           x, y, .... 

我试过了:

list(zip(df.Text1,df.Text2,df.Text3,...)): 

这可行,但格式不理想。

还有:

df.apply(lambda x: ', '.join(x.astype(str)), axis=1): 

这给出了所需的格式,但答案将包含所有字段。

最好的方法是什么?非常感谢!

【问题讨论】:

    标签: python pandas merge


    【解决方案1】:

    矢量化解:

    In [65]: df['Text'] = df.filter(regex='^Text\d+').add(', ').sum(1).str.rstrip(', ')
    
    In [66]: df
    Out[66]:
       ID1 ID2  Day Text1 Text2 Text3     Text
    0  111   A    1     a     b     c  a, b, c
    1  222   B    2     i     j     k  i, j, k
    2  333   C    3     x     y     z  x, y, z
    

    【讨论】:

      【解决方案2】:

      您的代码非常接近。您只需在 df[text_cols] 上使用 apply,其中 text_cols 是您要合并到新列中的列的列表。

      df['Text'] = df[text_cols].apply(lambda x: ''.join(x), axis=1)
      

      【讨论】:

        【解决方案3】:

        还有一个矢量化的join

        >>> df['Text'] = df.filter(regex='^Text\d+').sum(1).str.join(', ')
        >>> df
           ID1 ID2  Day Text1 Text2 Text3     Text
        0  111   A    1     a     b     c  a, b, c
        1  222   B    2     i     j     k  i, j, k
        2  333   C    3     x     y     z  x, y, z
        

        【讨论】:

          【解决方案4】:

          其他解决方案很棒,我想提供一个使用 cat() 函数的答案。

          df['text'] = df[0].str.cat([df[i] for i in df.columns[1:]],sep=',')
          

          希望对你有帮助:)

          【讨论】:

            猜你喜欢
            • 2018-08-25
            • 1970-01-01
            • 2017-05-28
            • 1970-01-01
            • 2019-07-02
            • 2019-06-29
            • 2017-04-17
            • 2021-01-08
            • 1970-01-01
            相关资源
            最近更新 更多