1

I have a data frame with strings of equal length (10). I want to "explode" this column into 10 columns. No matter what solution I try, there is a leading empty column. Existing solutions give me this problem, so needless to say existing answers to this question are not satisfactory.

import pandas as pd

df = pd.DataFrame(['tenletters', 'alsotenten', 'letter10!!', 'ten10lette'], 
    columns=['col1'])

df2 = pd.DataFrame(df['col1'].str.split('').tolist())
  0  1  2  3  4  5  6  7  8  9 10 11
0    t  e  n  l  e  t  t  e  r  s   
1    a  l  s  o  t  e  n  t  e  n   
2    l  e  t  t  e  r  1  0  !  !   
3    t  e  n  1  0  l  e  t  t  e   

How can I do this the proper way (i.e., without a leading empty column)?

3 Answers 3

3

Use map

df_final = pd.DataFrame(df['col1'].map(list).tolist())

Out[44]:
   0  1  2  3  4  5  6  7  8  9
0  t  e  n  l  e  t  t  e  r  s
1  a  l  s  o  t  e  n  t  e  n
2  l  e  t  t  e  r  1  0  !  !
3  t  e  n  1  0  l  e  t  t  e
Sign up to request clarification or add additional context in comments.

Comments

1
>>> pd.DataFrame(df['col1'].apply(list).tolist())
   0  1  2  3  4  5  6  7  8  9
0  t  e  n  l  e  t  t  e  r  s
1  a  l  s  o  t  e  n  t  e  n
2  l  e  t  t  e  r  1  0  !  !
3  t  e  n  1  0  l  e  t  t  e

1 Comment

the .values seems redundant
0

You use pd.Series.apply

df.col1.apply(lambda x: pd.Series(list(x)))

   0  1  2  3  4  5  6  7  8  9
0  t  e  n  l  e  t  t  e  r  s
1  a  l  s  o  t  e  n  t  e  n
2  l  e  t  t  e  r  1  0  !  !
3  t  e  n  1  0  l  e  t  t  e

You can try this for fun. (Not a performant solution)

Using pd.Series.str.extractall

df.col1.str.extractall(r'(.)').unstack()

       0
match  0  1  2  3  4  5  6  7  8  9
0      t  e  n  l  e  t  t  e  r  s
1      a  l  s  o  t  e  n  t  e  n
2      l  e  t  t  e  r  1  0  !  !
3      t  e  n  1  0  l  e  t  t  e

Note: The column is MultiIndex to make it a single-level df.columns = d.columns.get_level_values(1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.