jamo
jamo

Reputation: 91

How to split strings in data frame and put comma as delimiter

I have below data frame using Pandas:

    a   b
1   AC  GA
2   AT  AA
3   GG  TG
4   GC  GA
5   CG  GG

and I would like to split each string and put comma as delimiter:

         a  b
    1   A,C G,A
    2   A,T A,A
    3   G,G T,G
    4   G,C G,A
    5   C,G G,G

any suggestions is appreciated.

Upvotes: 1

Views: 70

Answers (3)

piRSquared
piRSquared

Reputation: 294278

stack/unstack

df.stack().str.join(',').unstack()

     a    b
1  A,C  G,A
2  A,T  A,A
3  G,G  T,G
4  G,C  G,A
5  C,G  G,G

Upvotes: 3

BENY
BENY

Reputation: 323236

IIUC

def yfunc(x):
   return x.apply(lambda x : ','.join(list(x)))
df.apply(yfunc)
Out[561]: 
     a    b
1  A,C  G,A
2  A,T  A,A
3  G,G  T,G
4  G,C  G,A
5  C,G  G,G

Upvotes: 2

Rakesh
Rakesh

Reputation: 82765

Use applymap(",".join)

Ex:

df = df.applymap(",".join)
print(df)

Output:

     a    b
0  A,C  G,A
1  A,T  A,A
2  G,G  T,G
3  C,G  G,G

Upvotes: 3

Related Questions