How to handle errors while splitting a column using a separator if no row contain that separator?

Viewed 28

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.

1 Answers

You can use Try and Except or Define regular routine to define interchangable object instead of blank or wrong format

You can Use these Routings:

if not bool(myBlankObject):
   #define new value
   myBlankObject = someValue

or you can use this routing:

try:
   #raise Error

except Exception as e:
   myBlakObject = someValue
   #or do sth

I recommend you to do the first option because you need to define something else for doing preprocessing of data; therefore, you need define new object instead of empty or None or blank object

Related