可以通过构造可迭代的函数来实现。循环dataframe的每一行,然后使用yield
迭代器返回数据,在外部使用next()
来获取函数的结果
示例代码
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.random(size=(10, 3)))
def iter_df():
for _i, series in df.iterrows(): # 循环每一行
yield _i, series
iter_tool = iter_df()
for i in range(3):
row_i, row_value = next(iter_tool)
print(row_i, row_value)
得到的结果:
0 0 0.780242
1 0.005111
2 0.260883
Name: 0, dtype: float64
1 0 0.855790
1 0.067688
2 0.909780
Name: 1, dtype: float64
2 0 0.995463
1 0.854817
2 0.752533
Name: 2, dtype: float64