Oftentimes, there will be something a bit off with the string data in your dataset. You may want to replace some characters, change the case, or strip the whitespace. You know, anything you normally need to do with strings.
Now this might lead you to want to loop through each row and manipulate the data, but before you do that, step back and lean into vectorization.
Series provides a way to use vectorized string methods in a property named
str and the vectorized methods are then available.
Let's take a look at some examples that require us to use these methods.
# Setup import os import pandas as pd from utils import make_chaos pd.options.display.max_rows = 10 transactions = pd.read_csv(os.path.join('data', 'transactions.csv'), index_col=0) # Pay no attention to the person behind the curtain make_chaos(transactions, 42, ['sender'], lambda val: '$' + val) make_chaos(transactions, 88, ['receiver'], lambda val: val.upper())
When CashBox first got started, usernames were allowed to start with a dollar sign. As time progressed, they changed their mind. They made a mass update to the system. However, someone on the Customer Support team reported that there are some records in the
DataFrame still showing some senders whose user name still had the $ prefix.
In order to get ahold of those rows where the sender starts with a $, we can use the
Series.str.startswith method. This will return a boolean
Series which we can use as an index.
42 rows × 4 columns
We can now just go ahead and replace all
$ with an empty string, essentially removing all
$ from every sender by using the
# Replace all "$" in the sender field with an empty string transactions.sender = transactions.sender.str.replace('$', '') # Verify we got them all len(transactions[transactions.sender.str.startswith('$')])
When you want to select or merge by specific values, the case, you know upper case or lower case, matters.
Our CashBox customer support representative also raised another issue for us to take a look at. All usernames should be lowercased, but they have reported that they noticed the
receiver column has some uppercased values.
We can get a handle on those by using the
Series.str.isupper method which will return a boolean
Series that we can use for an index.
88 rows × 4 columns
So let's select the rows we want from
transactions and then update the
receiver column to the matching lowercased value. We can use the
Series.str.lower vectorized method.
# Update the receiver column of the specific rows that are uppercased. transactions.loc[transactions.receiver.str.isupper(), 'receiver'] = transactions.receiver.str.lower() # Verify that we got them len(transactions[transactions.receiver.str.isupper()])