python 历遍df
时间: 2023-09-02 17:11:41 浏览: 34
使用pandas库中的iterrows()方法历遍DataFrame。
示例代码:
```
import pandas as pd
# 创建DataFrame
df = pd.DataFrame({'col1': [1, 2, 3], 'col2': ['a', 'b', 'c']})
# 使用iterrows()方法历遍DataFrame
for index, row in df.iterrows():
print(f"Index: {index}")
print(f"Values: {row['col1']}, {row['col2']}")
```
输出结果:
```
Index: 0
Values: 1, a
Index: 1
Values: 2, b
Index: 2
Values: 3, c
```
相关问题
python 历遍dict
以下是两种Python遍历字典的方法:
1. 使用for循环遍历字典的键:
```python
book = {'title': 'Python', 'author': '--', 'press': '人生苦短,我用python'}
for key in book:
print(key) # 输出结果:title author press
```
2. 使用items()方法遍历字典的键值对:
```python
book = {'title': 'Python', 'author': '--', 'press': '人生苦短,我用python'}
for key, value in book.items():
print(key, value) # 输出结果:title Python author -- press 人生苦短,我用python
```
python 历遍列表
可以使用 for 循环来历遍列表,例如:
```
my_list = [1, 2, 3, 4, 5]
for item in my_list:
print(item)
```
这将输出列表中的每个元素。