- [Instructor] In this self-check exercise,
we'd like you to do a little bit of
data transformation using a data frame.
In particular, we want you to assume
that a U.S. phone number must be in this format
instead of what we just demonstrated to you
in the preceding video.
So we'll have three digits in parentheses,
followed by a space, three digits followed by a dash,
and the last four digits of the phone number.
What we want you to do in this exercise
is modify the get_formatted_phone function
that I showed you in the preceding video
to return a phone number in this new format,
then go ahead and recreate the data frame that we showed you
and apply the get_formatted_phone function
to every element in the phone column.
Go ahead and pause this video to give that a shot,
then come back to see the answer.
Okay, let's go ahead and import pandas
in the regular expression module
and let's define our contacts list
and turn it into a data frame.
The key change in this example
is to the get_formatted_phone function
and, as you can see here, we've updated the definition
of get_formatted_phone.
Now, we're still using this full match call
to capture the first three digits,
the second three digits, and the last four digits
in our two phone numbers,
but we have an if else statement at this point
and what we're going to do is use the capability
of unpacking a tuple to call the groups function
and split the phone number into
part one, part two, and part three.
Then we're going to format that data,
so we have a left parenthesis, plus part one,
plus a right parenthesis, and a space,
so a little string concatenation here,
then we add in part two, then we add a dash,
and then we add in part three.
So this creates the format that we showed you back up here
in the problem statement.
Let's define that function.
By the way, if there is no match,
we simply return the original value in its original form
and do not modify that in the series.
In this case, we went ahead and simply
took the result of the map operation
and assigned it directly back
to the context data frame's phone column.
Let's execute that and then just to confirm
that, indeed, the data was formatted correctly,
we evaluate the data frame.
By the way, I just wanna revisit this
because, again, in the context of Jupyter Notebooks here,
notice the nice-looking formatting
that you get for a data frame.
Notice the little bit of visual interactivity you get
as you move the cursor over each row,
it highlights that row so that you can see it
a little bit better and, again, this is the result
of the map operation that took phone numbers
in this format and turned them into the format we specified.