TransWikia.com

Vertical concatenation in a df based on column value_python

Data Science Asked on March 22, 2021

Is there any way to concatenate vertically a specific column from my df (concat1), considering/filtering values from another column (col_value)?

My df looks like this:

col_value         concat1    
data1             x;y;z    
data1             d;f;h
data1             p;c;j
data2             s;k;a 
data3             a;w;q
data2             o;i;s 
data3             e;q;j
data4             d;f;n
data4             q;f;k

Expected output:

col_value         vertical_concat

data1             x;y;z;d;f;h;p;c;j    
data1             x;y;z;d;f;h;p;c;j
data1             x;y;z;d;f;h;p;c;j
data2             s;k;a;o;i;s
data3             a;w;q;e;q;j
data2             s;k;a;o;i;s
data3             a;w;q;e;q;j
data4             d;f;n;q;f;k
data4             d;f;n;q;f;k

Many thanks in advance

One Answer

Try:

a = ["data1"      
,"data1"         
,"data1"         
,"data2"         
,"data3"         
,"data2"         
,"data3"         
,"data4"         
,"data4"]     

b = ["x;y;z"  
    ,"d;f;h"
    ,"p;c;j"
    ,"s;k;a"
    ,"a;w;q"
    ,"o;i;s"
    ,"e;q;j"
    ,"d;f;n"
    ,"q;f;k"]

e = pd.DataFrame({"col_value":a,"concat1":b})


e["vertical_concat"] = e.groupby("col_value").transform(lambda x: ";".join(x.unique()))

Output:

enter image description here

Correct answer by Julio Jesus on March 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP