dataframe遍历每一行
时间: 2023-09-20 18:07:31 浏览: 86
您可以使用 `iterrows()` 方法来遍历 Pandas DataFrame 中的每一行。
下面是一个简单的例子,演示如何使用 `iterrows()` 方法来遍历一个 DataFrame:
``` python
import pandas as pd
# 创建一个DataFrame
df = pd.DataFrame({
'姓名': ['张三', '李四', '王五'],
'年龄': [20, 25, 30],
'性别': ['男', '女', '男']
})
# 遍历DataFrame中的每一行
for index, row in df.iterrows():
print(f"姓名:{row['姓名']},年龄:{row['年龄']},性别:{row['性别']}")
```
输出结果如下:
```
姓名:张三,年龄:20,性别:男
姓名:李四,年龄:25,性别:女
姓名:王五,年龄:30,性别:男
```
在上面的示例中,我们使用 `iterrows()` 方法遍历了 DataFrame 中的每一行,并通过 `row` 变量获取了每一行的数据。在 `for` 循环的迭代过程中,`index` 变量代表了当前行的索引。
相关问题
dataframe遍历每个元素
可以使用`iterrows()`方法来遍历DataFrame中的每一行,然后使用`iteritems()`方法来遍历每一行中的每一个元素。
例如,假设有以下DataFrame:
```
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
```
则可以使用以下代码遍历每一个元素:
```
for index, row in df.iterrows():
for column, value in row.iteritems():
print(f"Element at ({index}, {column}) is {value}")
```
输出结果如下:
```
Element at (0, A) is 1
Element at (0, B) is 4
Element at (0, C) is 7
Element at (1, A) is 2
Element at (1, B) is 5
Element at (1, C) is 8
Element at (2, A) is 3
Element at (2, B) is 6
Element at (2, C) is 9
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)