Pandas DataFrame itertuples() 返回的 NamedTuple 的类型提示

Jay*_*nal 10 python typing type-hinting

ITERTUPLES是迭代 pandas DF 的好方法,它返回一个命名元组。

import pandas as pd
import numpy as np

df = pd.DataFrame({'num_legs': [4, 2], 'num_wings': [0, 2]},index=['dog', 'hawk'])
for row in df.itertuples():
    print(type(row))
    print(row)
Run Code Online (Sandbox Code Playgroud)
<class 'pandas.core.frame.Pandas'>
Pandas(Index='dog', num_legs=4, num_wings=0)
<class 'pandas.core.frame.Pandas'>
Pandas(Index='hawk', num_legs=2, num_wings=2)
Run Code Online (Sandbox Code Playgroud)

如果有的话,向返回的命名元组添加类型提示的正确方法是什么?

kws*_*wsp 2

我认为这是不可能的,因为您的数据帧可以具有任何任意数据类型,因此元组将具有数据帧中存在的任何任意数据类型。同样,您不能使用 Python 类型提示来指定 DataFrame 的列类型,您也不能显式键入那些命名元组。

如果您在进入 for 循环之前需要列的类型信息,您当然可以使用df.dtypes,它会为您提供包含列类型的 Series。