dataframe遍历每一行
时间: 2023-09-19 20:08:23 浏览: 47
遍历DataFrame每一行的常见方法有以下两种:
1. iterrows()方法
iterrows()方法返回一个生成器,可以逐行遍历DataFrame。每次迭代返回一个元组,包含当前行的索引和当前行的数据。
例如:
```python
import pandas as pd
df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
for index, row in df.iterrows():
print(f"Row {index}:\n{row}\n")
```
输出:
```
Row 0:
col1 1
col2 3
Name: 0, dtype: int64
Row 1:
col1 2
col2 4
Name: 1, dtype: int64
```
2. itertuples()方法
itertuples()方法返回一个生成器,可以逐行遍历DataFrame。每次迭代返回一个命名元组,包含当前行的索引和当前行的数据。
例如:
```python
import pandas as pd
df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
for row in df.itertuples():
print(row)
```
输出:
```
Pandas(Index=0, col1=1, col2=3)
Pandas(Index=1, col1=2, col2=4)
```
注意:使用iterrows()和itertuples()方法遍历DataFrame的效率不高,如果DataFrame非常大,建议使用向量化操作来处理数据。