namedtuple

Python のデータ型

Jason Myers

Instructor

namedtupleとは?

  • 各位置(列)に名前を持つタプル
  • 各要素が同じプロパティを持つことを保証
  • pandas DataFrameの行の代替
Python のデータ型

namedtupleの作成

  • 名前とフィールドのリストを渡す
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)
Python のデータ型

最初の要素を出力

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')
Python のデータ型

namedtupleの活用

  • 各フィールドは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 ...
Python のデータ型

練習しましょう!

Python のデータ型

Preparing Video For Download...