0
$\begingroup$

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

$\endgroup$
1
$\begingroup$

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

$\endgroup$
1
  • $\begingroup$ thank you so much, it works! $\endgroup$ – Isa Mar 8 at 10:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.