2016-01-12 34 views
1

我有我想拆分的DataFrame列。 例如:如何拆分python中的DataFrame列

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

的信息被存儲在一個數據幀。我如何將數據框更改爲此?

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

謝謝

回答

1

您正在尋找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 

如果您使用的是0.16.1年長的大熊貓,要使用return_type='frame',而不是expand=True

0

您可以使用DataFrame構造函數:

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