Skip to main content
 首页 » 编程设计

python之在 Pandas 的多行中连接多列

2025年05月04日21mq0036

我有一个 Pandas 数据框。我想基于一个带有标识符的列来连接多个列。可能有不止一行的列需要连接。我只使用字符串。

例如,我有一个如下所示的数据集:

 Identifier     Op1 Op2 Op3 
 A     str_1    str_2   str_3 
 B     str_4    str_5   str_6 
 B     str_7    str_8   str_9 
 B     str_10   str_11  str_12 
 C     str_13   str_14  str_15  
 C     str_16   str_17  str_18 

我需要将 Op1、Op2 和 Op3 中的每个人串联起来。如果同一“标识符”在多行上,我需要将 Op1、Op2 和 Op3 列连接起来,然后再与第一列连接起来。

所以我的最终结果应该是这样的:

 Identifier Ops 
 A  str_1 str_2 str_3 
 B  str_4 str_5 str_6 str_7 str_8 str_9 str_10 str_11 str_12 
 C  str_13 str_14 str_15 str_16 str_17 str_18 

每个“事物”之间也应该有一个空格。所以像 'str_8 str_9' 而不是 'str_8str_9'

如果它比 pandas 更容易使用,我也在 sqlite3 中有这个表。

我该怎么做?

谢谢

请您参考如下方法:

将您的输入数据转换为 csv 文件,我执行了以下操作,效果很好。

import pandas as pd 
 
DF = pd.read_csv("CombinerData.csv") 
 
print DF 
print  
 
def combine_Columns_Into_New_Column(DF, columns_To_Combine, new_Column_Name): 
    DF[new_Column_Name] = '' 
    for Col in columns_To_Combine: 
        DF[new_Column_Name] += DF[Col].map(str) + ' ' 
    DF = DF.drop(columns_To_Combine, axis=1) 
    DF = DF.groupby(by=['Identifier']).sum() 
 
    return DF 
 
DF = combine_Columns_Into_New_Column(DF, ['Op1','Op2','Op3'],'Ops') 
 
print DF 

输出:

                                                          Ops 
Identifier                                                    
A                                          str_1 str_2 str_3  
B           str_4 str_5 str_6 str_7 str_8 str_9 str_10 str... 
C                 str_13 str_14 str_15  str_16 str_17 str_18  

输入文件:

Identifier,Op1,Op2,Op3 
A,str_1,str_2,str_3 
B,str_4,str_5,str_6 
B,str_7,str_8,str_9 
B,str_10,str_11,str_12 
C,str_13,str_14,str_15  
C,str_16,str_17,str_18