2017-07-27 62 views
2

如何拆分pandas列并将新结果追加到数据框?我也希望那里没有空白。我期望输出的拆分pandas列并将新结果追加到数据框中

例子:

col1 
Smith, John 
Smith, John 

col2    
Smith 
Smith 

col3 
John 
John 

我一直但是lambda函数尝试这是不附加我怎么想它的结果。

df_split = df1['col1'].apply(lambda x: pd.Series(x.split(','))) 
df1['col2']= df_split.apply(lambda x: x[0]) 
df1['col3']= df_split.apply(lambda x: x[1]) 

我最终得到

col2 col3 
Smith Smith 
John John 

回答

4

使用Series.str.split(..., expand=True)

In [1148]: df[['col2', 'col3']] = df.col1.str.split(',\s+', expand=True); df 
Out[1148]: 
      col1 col2 col3 
0 Smith, John Smith John 
1 Smith, John Smith John 
+0

谢谢! \ s +做什么? \ s是空格,但是“+”表示什么? – OptimusPrime

+0

@OptimusPrime如果你有多个空白(抢占地带):) –

+0

另外,作为一个新用户,你知道你可以[接受答案](https://stackoverflow.com/help/someone-answers)帮助。 –

相关问题