df.iterrows() 是 Pandas 中的一个方法,用于在遍历 DataFrame 时,逐行返回每一行的索引和数据
df.iterrows() 是 Pandas 中的一个方法,用于在遍历 DataFrame 时,逐行返回每一行的索引和数据。它生成一个迭代器,每次迭代时返回一个 (index, Series) 对,index 是行索引,Series 是该行的数据。
详细解释
df.iterrows():- 这个方法遍历
DataFrame的每一行。 - 每次迭代时,返回的是
(index, Series),其中index是行的索引,Series是表示行数据的 PandasSeries对象。
- 这个方法遍历
示例
假设有一个 DataFrame df:
import pandas as pd data = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]} df = pd.DataFrame(data)
这个 DataFrame 看起来像这样:
| A | B | C | |
|---|---|---|---|
| 0 | 1 | 4 | 7 |
| 1 | 2 | 5 | 8 |
| 2 | 3 | 6 | 9 |
如果使用 iterrows() 迭代:
for index, row in df.iterrows(): print(index) print(row)
输出将是:
0 A 1 B 4 C 7 Name: 0, dtype: int64 1 A 2 B 5 C 8 Name: 1, dtype: int64 2 A 3 B 6 C 9 Name: 2, dtype: int64
作用总结
- 遍历每一行:
iterrows()允许你逐行遍历 DataFrame 的数据,非常适合需要逐行处理数据的情况。 - 返回行索引和行数据:在每次迭代中,你会得到当前行的索引和一个包含该行数据的
Series对象。 - 灵活的数据操作:你可以在遍历过程中对行数据进行任何操作,例如数据处理、条件判断、存储等。
注意事项
iterrows()的性能在处理大数据集时可能不如矢量化操作高效,因为它逐行遍历,不能充分利用 Pandas 的优化。iterrows()返回的是行的副本,而不是视图,对row的修改不会影响原始 DataFrame。
因此,df.iterrows() 适用于需要逐行处理数据的场景,但在可能的情况下,应该优先选择更高效的矢量化操作。

浙公网安备 33010602011771号