Skip to content Skip to sidebar Skip to footer

How To Split A Dataframe Column In Python

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

Solution 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

Solution 2:

You can use DataFrame constructor:

printdf#   0  1      2#0  a  b  c-d-e#1  f  g  h-i-j#2  k  l  m-n-odf[[2, 3, 4]] = pd.DataFrame([ x.split('-') for x indf[2].tolist() ])
printdf#   0  1  2  3  4#0  a  b  c  d  e#1  f  g  h  i  j#2  k  l  m  n  o

Post a Comment for "How To Split A Dataframe Column In Python"