可以使用iterrows()方法来遍历Pandas数据框并获取值和行号。以下是一个示例:
import pandas as pd
# 创建一个示例数据框
data = {'Name': ['Tom', 'Nick', 'John', 'Peter'],
'Age': [20, 25, 30, 35],
'City': ['New York', 'Paris', 'London', 'Tokyo']}
df = pd.DataFrame(data)
# 使用iterrows()方法遍历数据框
for index, row in df.iterrows():
print('Row Index:', index)
print('Values:')
print('Name:', row['Name'])
print('Age:', row['Age'])
print('City:', row['City'])
print('---')
输出结果如下:
Row Index: 0
Values:
Name: Tom
Age: 20
City: New York
---
Row Index: 1
Values:
Name: Nick
Age: 25
City: Paris
---
Row Index: 2
Values:
Name: John
Age: 30
City: London
---
Row Index: 3
Values:
Name: Peter
Age: 35
City: Tokyo
---
在上述示例中,使用iterrows()方法遍历数据框,并通过index和row变量获取行号和值。然后可以根据需要对每一行的值进行处理。