遍历dataframe xiaoyuzhou
时间: 2025-06-02 17:40:32 浏览: 15
### 遍历 Pandas DataFrame 的方法
#### 使用 `iterrows()` 方法遍历 DataFrame 行
`iterrows()` 是 Pandas 提供的一种常用方法,用于逐行遍历 DataFrame。该方法返回的是索引和每一行的数据作为 Series 对象。
```python
import pandas as pd
def iterrows_example():
# 创建一个示例 DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35], 'Score': [85, 90, 88]}
df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)
# 使用 iterrows() 遍历
for index, row in df.iterrows():
print(f"Index: {index}, Name: {row['Name']}, Age: {row['Age']}, Score: {row['Score']}")
# 调用函数
iterrows_example()
```
这种方法适用于需要访问每行的具体列值的情况[^2]。
#### 使用 `itertuples()` 方法提高性能
当不需要修改原始数据时,可以考虑使用 `itertuples()` 来代替 `iterrows()`。此方式通常会带来更好的性能表现,因为它返回的是命名元组而不是 Series 对象。
```python
def itertuples_example():
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35], 'Score': [85, 90, 88]}
df = pd.DataFrame(data)
for row in df.itertuples(index=True):
print(f"Index: {row.Index}, Name: {row.Name}, Age: {row.Age}, Score: {row.Score}")
# 执行例子
itertuples_example()
```
这种方式不仅速度快而且更易于读取字段名称[^4]。
#### 应用向量化操作优化效率
如果只是简单地对各行列执行相同的操作,则应优先尝试利用 Pandas 或 NumPy 内置的支持向量化的功能来进行批量计算,这往往比显式的循环更加高效。
```python
def vectorized_operation_example():
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35], 'Score': [85, 90, 88]}
df = pd.DataFrame(data)
# 增加一个新的列表示年龄增加五岁后的结果
df['Increased_Age'] = df['Age'].apply(lambda x: x + 5)
print(df[['Name','Age','Increased_Age']])
vectorized_operation_example()
```
通过上述三种不同的技术手段可以选择最适合具体应用场景的方式来实现高效的 DataFrame 数据遍历[^1]。
阅读全文
相关推荐














