I have a dataframe column which contains the name of people
Name
-------
Doe,John
Joe,Don
Hanks
I split this into two columns using the comma as a separator
x[['lastname','firstname']].str.split(',',1,expand = True)
and obtain a new dataframe
lastname | firstname
--------------------
Doe | John
Joe | Don
Hanks |
Notice that for Hanks, the last name is blank as expected since there is no comma in this case. Now this is an hourly file and as long as there is at least one name with a comma, the code runs fine and creates the fistname and lastname columns. However in some rare occasions, all the names in the column of that hourly file has just a single word the last name. This gives an error in str.split since there is no row that satisfies the splitting criteria using the comma as a separator.
Question: How do I handle this error in Python. In case all the names in the file has only a single word and no row has a comma which can act as a separator, I want put the single word in the first column and pur default blank in the second column after splitting.