Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

python - How to merge two dataframes with multiple element from one column

I try to merge a new dataframe based on a dataframe composed by element and a other dataframe with unique dataframe.

The dataframe1 :

        col1                 
0       A1               
1       A1,A5             
2       A1               
3       A2,A9,A3           
4       A3                         

The dataframe2 :

        column1        column2      
0       A1             DE   
1       A2             DZ    
2       A3             DA  
3       A4             AC     
4       A5             RC       
5       A6             UC     
6       A7             TC       
7       A8             VC 
8       A9             WC
9       A10            XC  

The final dataframe :

        col1         column1        column2       
0       A1           A1             DE    
1       A1,A5        A1             DE
2       A1,A5        A5             RC
2       A1           A1             DE    
3       A2,A9,A3     A2             DZ       
4       A2,A9,A3     A9             WC         
5       A2,A9,A3     A3             DA
6       A3           A3             DA

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use DataFrame.explode by splitted values with DataFrame.merge and left join:

df = (df1.assign(column1 = df1['col1'].str.split(','))
         .explode('column1')
         .merge(df2, on='column1',how='left'))
print (df)
      col1 column1 column2
0        A1      A1      DE
1     A1,A5      A1      DE
2     A1,A5      A5      RC
3        A1      A1      DE
4  A2,A9,A3      A2      DZ
5  A2,A9,A3      A9      WC
6  A2,A9,A3      A3      DA
7        A3      A3      DA

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...