将Pandas列拆分并将新结果附加到数据框中

4
如何将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
3个回答

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

谢谢!\s+是什么作用?\s代表空白字符,但+又是做什么的呢? - OptimusPrime
@OptimusPrime 如果有多个空格(预防性剥离):) - cs95
expand=True是什么意思? - OptimusPrime
@OptimusPrime 将每个拆分的项目放入其自己的列中。 - cs95

4

1

如果您只想在分割后存储第一个字符串,请使用以下方法

df['col2'] = df['col1'].str.split(',', 1).str[0] 

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接