I have a dataframe that has column 'name'. With values like 'James Cameron'. I'd like to split it out into 2 new columns 'First_Name' and 'Last_Name', but there is no delimiter in the data so I am not quite sure how. I realize that 'James' is in position [0] and 'Cameron' is in position [1], but I am not sure you can recognize that without the delimiter
df = pd.DataFrame({'name':['James Cameron','Martin Sheen'], 'Id':[1,2]}) df EDIT:
Vaishali's answer below worked perfectly, for the dataframe I had provided. I created that dataframe as an example though. My real code looks like this"
data[['First_Name','Last_Name']] = data.director_name.str.split(' ', expand = True) and that unfortunately, is throwing an error:
'Columns must be same length as key' The column holds the same values as my example though. Any suggestions?
Thanks
03 Answers
You can split on space
df[['Name', 'Lastname']] = df.name.str.split(' ', expand = True) Id name Name Lastname 0 1 James Cameron James Cameron 1 2 Martin Sheen Martin Sheen EDIT: Handling the error 'Columns must be same length as key'. The data might have some names with more than one space, eg: George Martin Jr. In that case, one way is to split on space and use the first and the second string, ignoring third if it exists
df['First_Name'] = df.name.str.split(' ', expand = True)[0] df['Last_Name'] = df.name.str.split(' ', expand = True)[1] 2Slightly different way of doing this:
df[['first_name', 'last_name']] = df.apply(lambda row: row['name'].split(), axis=1) df Id name first_name last_name 0 1 James Cameron James Cameron 1 2 Martin Sheen Martin Sheen I like this method... Not as quick as simply splitting but it drops in column names in a very convenient way.
df.join(df.name.str.extract('(?P<First>\S+)\s+(?P<Last>\S+)', expand=True)) Id name First Last 0 1 James Cameron James Cameron 1 2 Martin Sheen Martin Sheen 0