1

i have DataFrame column which i want to split. For example:

     0     1     2
0    a     b     c-d-e
1    f     g     h-i-j
2    k     l     m-n-o

The information is stored in a DataFrame. How can I change the dataframe to this?

     0     1     2     3     4
0    a     b     c     d     e
1    f     g     h     i     j
2    k     l     m     n     o

Thank you

2 Answers 2

1

You're looking for Series.str.split

>>> print df[2].str.split('-', expand=True)
   0  1  2
0  c  d  e
1  h  i  j
2  m  n  o

>>> pd.concat((df[[0, 1]], df[2].str.split('-', expand=True)), axis=1, ignore_index=True)
   0  1  2  3  4
0  a  b  c  d  e
1  f  g  h  i  j
2  k  l  m  n  o

If you're using pandas older than 0.16.1, you want to use return_type='frame' instead of expand=True

Sign up to request clarification or add additional context in comments.

Comments

0

You can use DataFrame constructor:

print df

#   0  1      2
#0  a  b  c-d-e
#1  f  g  h-i-j
#2  k  l  m-n-o

df[[2, 3, 4]] = pd.DataFrame([ x.split('-') for x in df[2].tolist() ])
print df

#   0  1  2  3  4
#0  a  b  c  d  e
#1  f  g  h  i  j
#2  k  l  m  n  o

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.