遍历pandas行可以使用iterrows()方法。以下是一个示例代码:
import pandas as pd
# 创建一个DataFrame
data = {'Name': ['Tom', 'Nick', 'John'],
'Age': [28, 30, 25],
'City': ['London', 'New York', 'Paris']}
df = pd.DataFrame(data)
# 使用iterrows()遍历DataFrame的行
for index, row in df.iterrows():
print(f"Index: {index}")
print(f"Name: {row['Name']}")
print(f"Age: {row['Age']}")
print(f"City: {row['City']}")
print("------")
输出结果如下:
Index: 0
Name: Tom
Age: 28
City: London
------
Index: 1
Name: Nick
Age: 30
City: New York
------
Index: 2
Name: John
Age: 25
City: Paris
------
通过使用iterrows()方法,可以遍历DataFrame的每一行,并对行中的每个元素进行处理。
上一篇:遍历pandas系列并格式化日期
下一篇:遍历pandas行以检查大量条件