Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a pandas column and append the new results to the dataframe

How can I split a pandas column and append the new results to the dataframe? I also want there to be no white space.

Example of my desired output:

col1
Smith, John
Smith, John

col2               
Smith
Smith

col3
John
John

I been trying this but the lambda function is not appending the results how I want it to.

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])

I end up getting

col2  col3
Smith Smith
John  John
like image 968
OptimusPrime Avatar asked Dec 24 '22 15:12

OptimusPrime


1 Answers

Use 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
like image 166
cs95 Avatar answered Jan 18 '23 22:01

cs95