pandas.DataFrame.itertuples#
- DataFrame.itertuples(index=True, name='Pandas')[源代码]#
将 DataFrame 行迭代为命名元组。
- 参数:
- indexbool, 默认 True
如果为 True,则返回索引作为元组的第一个元素。
- namestr 或 None,默认值为 “Pandas”
返回的命名元组的名称,或 None 返回普通元组。
- 返回:
- iterator
一个对象,用于迭代 DataFrame 中每行的命名元组,其中第一个字段可能是索引,后面的字段是列值。
另请参阅
DataFrame.iterrows将 DataFrame 行迭代为(索引,Series)对。
DataFrame.items迭代(列名,Series)对。
注意
如果列名是无效的 Python 标识符、重复的或以下划线开头,则它们将被重命名为位置名称。
示例
>>> df = pd.DataFrame( ... {"num_legs": [4, 2], "num_wings": [0, 2]}, index=["dog", "hawk"] ... ) >>> df num_legs num_wings dog 4 0 hawk 2 2 >>> for row in df.itertuples(): ... print(row) Pandas(Index='dog', num_legs=4, num_wings=0) Pandas(Index='hawk', num_legs=2, num_wings=2)
通过将 index 参数设置为 False,我们可以移除索引作为元组的第一个元素
>>> for row in df.itertuples(index=False): ... print(row) Pandas(num_legs=4, num_wings=0) Pandas(num_legs=2, num_wings=2)
通过设置 name 参数,我们可以为生成的命名元组设置自定义名称
>>> for row in df.itertuples(name="Animal"): ... print(row) Animal(Index='dog', num_legs=4, num_wings=0) Animal(Index='hawk', num_legs=2, num_wings=2)