Spencer
Spencer

Reputation: 59

Explode characters in column of strings into multiple columns

My Dataframe is like:

       col1
   0   AGCT
   1   AGCT

How to turn it like this:

   col1 col2 col3 col4
0   A     G    C    T
1   A     G    C    T

Upvotes: 0

Views: 151

Answers (2)

BENY
BENY

Reputation: 323226

IIUC

df=df.col1.apply(list).apply(pd.Series)
df
Out[645]: 
   0  1  2  3
0  A  G  C  T
1  A  G  C  T

If performance is matter :-)

pd.DataFrame(list(map(list,df.col1.values)))
Out[647]: 
   0  1  2  3
0  A  G  C  T
1  A  G  C  T

Upvotes: 2

cs95
cs95

Reputation: 402483

Option 1
list comprehension - You'd be surprised at how fast this is.

pd.DataFrame([list(x) for x in df.col1])

   0  1  2  3
0  A  G  C  T
1  A  G  C  T

Option 2
pd.Series.apply (less performant)

pd.DataFrame(df.col1.apply(list).tolist())

   0  1  2  3
0  A  G  C  T
1  A  G  C  T

Option 3
pd.Series.extractall + unstack (least performant)

df.col1.str.extractall('(.)')[0].unstack()

match  0  1  2  3
0      A  G  C  T
1      A  G  C  T

Upvotes: 3

Related Questions