December 2015
Beginner to intermediate
202 pages
4h
English
It is very common to find whitespace at the beginning, the end, or the inside of a string, whether it's data in a CSV file or data from another source. Use the following recipe to create a custom function to remove the whitespace from every row of a column in a Pandas DataFrame.
Continue using the customers DataFrame you created earlier, or import the file into a new DataFrame.
def remove_whitespace(x):
"""
Helper function to remove any blank space from a string
x: a string
"""
try:
# Remove spaces inside of the string
x = "".join(x.split())
except:
pass
return x
customers.last_name = customers.last_name.apply(remove_whitespace)We first create a custom function named remove_whitespace() ...
Read now
Unlock full access