namedtuple

Data Types in Python

Jason Myers

Instructor

What is a namedtuple?

  • A tuple where each position (column) has a name
  • Ensure each one has the same properties
  • Alternative to a pandas DataFrame row
Data Types in Python

Creating a namedtuple

  • Pass a name and a list of fields
from collections import namedtuple

Eatery = namedtuple('Eatery', ['name', 'location', 'park_id', ...: 'type_name'])
eateries = []
for eatery in nyc_eateries: details = Eatery(eatery['name'], eatery['location'], eatery['park_id'], eatery['type_name']) eateries.append(details)
Data Types in Python

Print the first element

print(eateries[0])
Eatery(name='Mapes Avenue Ballfields Mobile Food Truck',
location='Prospect Avenue, E. 181st Street',
park_id='X289', type_name='Mobile Food Truck')
Data Types in Python

Leveraging namedtuples

  • Each field is available as an attribute of the namedtuple
for eatery in eateries[:3]:
    print(eatery.name)
    print(eatery.park_id)
    print(eatery.location)
Mapes Avenue Ballfields Mobile Food Truck
X289
Prospect Avenue, E. 181st Street

Claremont Park Mobile Food Truck
X008
East 172 Street between Teller & Morris avenues ...
Data Types in Python

Let's practice!

Data Types in Python

Preparing Video For Download...