拆分pandas列并将新结果附加到数据帧

时间:2017-07-27 19:57:54

标签: python pandas lambda

如何拆分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

2 个答案:

答案 0 :(得分:5)

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

df[['col2', 'col3']] = df.col1.str.split(',\s+', expand=True); df

          col1   col2  col3
0  Smith, John  Smith  John
1  Smith, John  Smith  John

答案 1 :(得分:4)

我们可以使用Series.str.extract()方法:

In [157]: df[['col2','col3']] = df['col1'].str.extract('(\w+),\s*(\w+)', expand=True)

In [158]: df
Out[158]:
                 col1        col2   col3
0         Smith, John       Smith   John
1         Smith, John       Smith   John
2  Mustermann,    Max  Mustermann    Max
3          Last,First        Last  First

(\w+),\s*(\w+) is a RegEx (Regular Expression) explained here

相关问题