python 遍历df
时间: 2023-09-29 18:02:56 浏览: 85
遍历DataFrame可以使用iterrows()方法,代码示例如下:
```
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': ['a', 'b', 'c']})
for index, row in df.iterrows():
print(index, row['A'], row['B'])
```
输出结果为:
```
0 1 a
1 2 b
2 3 c
```
相关问题
python pandas 遍历DF
在Python的pandas库中,可以使用iterrows()方法来遍历DataFrame的行。下面是一个示例代码:
```python
import pandas as pd
# 创建一个示例DataFrame
data = {'Name': ['Tom', 'Nick', 'John'],
'Age': [20, 21, 22],
'City': ['New York', 'Paris', 'London']}
df = pd.DataFrame(data)
# 使用iterrows()方法遍历DataFrame的行
for index, row in df.iterrows():
print(row['Name'], row['Age'], row['City'])
```
这段代码会输出DataFrame中每一行的数据,包括Name、Age和City列的值。
python 遍历dataframe
Python遍历DataFrame可以使用for循环,也可以使用apply()函数。
使用for循环遍历DataFrame:
```python
import pandas as pd
# 创建DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
# 遍历DataFrame
for index, row in df.iterrows():
print(row['A'], row['B'])
```
使用apply()函数遍历DataFrame:
```python
import pandas as pd
# 创建DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
# 定义函数
def print_row(row):
print(row['A'], row['B'])
# 遍历DataFrame
df.apply(print_row, axis=1)
```
阅读全文
相关推荐














