float
values, such as['Brown, Sue', 98.6, 98.4, 98.7, 0.0]
Series
of five-digit ZIP Codes from a dictionary of city-name/five-digit-ZIP-Code key–value pairsimport pandas as pd
zips = pd.Series({'Boston': '02215', 'Miami': '3310'})
zips
Series
’ ZIP Code values (from the dictionary’s values)str
attribute of a Series
provides string-processing and various regular expression methodsstr
attribute’s match
method to check whether each ZIP Code is valid: zips.str.match(r'\d{5}')
match
applies the regular expression \d{5}
to each Series
elementSeries
containing True
for each valid element3310
, we might look for Miami ZIP Codes beginning with 331033101
and 33109
contains
instead of match
cities = pd.Series(['Boston, MA 02215', 'Miami, FL 33101'])
cities
cities.str.contains(r' [A-Z]{2} ')
cities.str.match(r' [A-Z]{2} ')
contacts = [['Mike Green', 'demo1@deitel.com', '5555555555'],
['Sue Brown', 'demo2@deitel.com', '5555551234']]
contactsdf = pd.DataFrame(contacts,
columns=['Name', 'Email', 'Phone'])
contactsdf
Series
method map
on the DataFrame
’s 'Phone'
columnmap
’s argument is a function that receives a value and returns the mapped valueget_formatted_phone
maps 10 consecutive digits into the format ###-###-####import re
def get_formatted_phone(value):
result = re.fullmatch(r'(\d{3})(\d{3})(\d{4})', value)
return '-'.join(result.groups()) if result else value
return
statement:result
is None
, returns value
unmodifiedresult.groups()
to get a tuple containing the captured substrings and pass that tuple to string method join
to concatenate the elements, separating each from the next with '-'
to form the mapped phone numberSeries
method map
returns a new Series
containing the results of calling its function argument for each value in the columnformatted_phone = contactsdf['Phone'].map(get_formatted_phone)
formatted_phone
DataFrame
contactsdf['Phone'] = formatted_phone
contactsdf
©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.
DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.