Python pandas.DataFrame.itertuples函数方法的使用

pandas.DataFrame.itertuples() 是一个非常高效的方法,用于按行迭代 DataFrame。它返回一个命名元组,元组的字段名为 DataFrame 的列名。该方法比 iterrows() 更快,因为它不会创建额外的 Series 对象。本文主要介绍一下Pandas中pandas.DataFrame.itertuples方法的使用。

DataFrame.itertuples(self, index=True, name='Pandas')                         [source]

将DataFrame行迭代为namedtuple。

参数

index : bool,默认为True

如果为True

则将索引作为元组的第一个元素返回。

name : strNone,默认为"Pandas"

返回的namedtuple的名称,

或者返回None以返回常规元组。

返回值

iterator

一个对象,用于遍历DataFrame中每一行的namedtuple

第一个字段可能是索引,而后面的字段是列值。

Notes

如果列名是无效的Python标识符,重复出现或以下划线开头,则列名将重命名为位置名。具有大量列(> 255)时,将返回常规元组。

例子

1)按行修改 DataFrame 中的数据

import pandas as pd

df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': [4, 5, 6]
})

# 修改 B 列的值
for row in df.itertuples():
    df.at[row.Index, 'B'] = row.B * 2

print(df)

2)使用 itertuples() 默认迭代(包括索引)

import pandas as pd

# 创建一个 DataFrame
df = pd.DataFrame({'num_legs': [4, 2], 'num_wings': [0, 2]},
                  index=['dog', 'hawk'])

# 显示 DataFrame
print("原始 DataFrame:")
print(df)

# 使用 itertuples() 默认迭代(包括索引)
print("\n使用 itertuples() 默认迭代:")
for row in df.itertuples():
    print(row)

3)使用 itertuples() 设置 index=False,去除索引作为元组的第一个元素

import pandas as pd

# 创建一个 DataFrame
df = pd.DataFrame({'num_legs': [4, 2], 'num_wings': [0, 2]},
                  index=['dog', 'hawk'])

# 使用 itertuples() 设置 index=False,去除索引作为元组的第一个元素
print("\n使用 itertuples(index=False) 去除索引:")
for row in df.itertuples(index=False):
    print(row)

4)自定义命名元组名称

import pandas as pd

# 创建一个 DataFrame
df = pd.DataFrame({'num_legs': [4, 2], 'num_wings': [0, 2]},
                  index=['dog', 'hawk'])



# 使用 itertuples() 设置 name='Animal',自定义命名元组名称
print("\n使用 itertuples(name='Animal') 设置自定义命名元组:")
for row in df.itertuples(name='Animal'):
    print(row)

推荐阅读
cjavapy编程之路首页