DataFrame.itertuples(self, index=True, name='Pandas') [source]
将DataFrame行迭代为namedtuple。
参数: | index : 如果为 则将索引作为元组的第一个元素返回。 name : 返回的namedtuple的名称, 或者返回 |
返回值: | iterator 一个对象,用于遍历 第一个字段可能是索引,而后面的字段是列值。 |
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)