0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

iterrows() と itertuples() の違い

Last updated at Posted at 2024-11-14

iterrows()

  • 戻り値: 各行を (インデックス, Series) のタプルとして返す
  • 速度: 比較的遅い
  • 使い方: 各行を Series として操作したい場合に便利

出力例

import pandas as pd

df = pd.DataFrame({
    'accession_id': ['A001', 'A002'],
    'type': ['RNASeq', 'ChIPSeq'],
    'experimental_fact': ['["fact1", " fact2 "]', '["fact3", " \'fact4\' "]']
})

for index, row in df.iterrows():
    print(index, row['accession_id'], row['type'], row['experimental_fact'])

出力:

0 A001 RNASeq ["fact1", " fact2 "]
1 A002 ChIPSeq ["fact3", " 'fact4' "]

itertuples()

  • 戻り値: 各行を namedtuple または普通のタプルとして返す(namedtuple がデフォルト)
  • 速度: 比較的速い
  • 使い方: 各行をタプルとして操作したい場合に便利

出力例

for row in df.itertuples():
    print(row.Index, row.accession_id, row.type, row.experimental_fact)

出力:

0 A001 RNASeq ["fact1", " fact2 "]
1 A002 ChIPSeq ["fact3", " 'fact4' "]

違いのまとめ

  • パフォーマンス: itertuples() の方が iterrows() よりも速い
  • 戻り値の形式: iterrows() は (インデックス, Series) のタプルを返し、itertuples() はタプル(デフォルトでは namedtuple)を返す
  • 使い勝手: iterrows() は各行を Series として操作できるため、列名でアクセスしやすいが、itertuples() はタプルとして操作するため、より軽量

具体的な用途やパフォーマンス要件に応じて、どちらを使うか選ぶと良い。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?