Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python 遍历dataframe

作者:刀魂使者   发布日期:2026-05-04   浏览:94

import pandas as pd

# 创建一个简单的 DataFrame
data = {
    '列1': [1, 2, 3],
    '列2': ['A', 'B', 'C']
}
df = pd.DataFrame(data)

# 方法1: 使用 iterrows() 遍历每一行
print("使用 iterrows() 遍历每一行:")
for index, row in df.iterrows():
    print(f"索引: {index}, 列1: {row['列1']}, 列2: {row['列2']}")

# 方法2: 使用 itertuples() 遍历每一行(性能更好)
print("\n使用 itertuples() 遍历每一行:")
for row in df.itertuples():
    print(f"索引: {row.Index}, 列1: {row.列1}, 列2: {row.列2}")

# 方法3: 使用 apply() 对每一行应用函数
print("\n使用 apply() 对每一行应用函数:")
def print_row(row):
    print(f"列1: {row['列1']}, 列2: {row['列2']}")

df.apply(print_row, axis=1)

解释说明:

  1. 创建 DataFrame:

    • 使用 pandas 库创建一个简单的 DataFrame,包含两列:列1列2
  2. 方法1: 使用 iterrows() 遍历每一行:

    • iterrows() 返回的是 (index, Series) 的元组对。
    • 这种方法适合需要访问索引和每一行数据的场景,但性能相对较差。
  3. 方法2: 使用 itertuples() 遍历每一行:

    • itertuples() 返回的是命名元组,性能比 iterrows() 更好。
    • 适用于需要高效遍历 DataFrame 的场景。
  4. 方法3: 使用 apply() 对每一行应用函数:

    • apply() 可以对每一行或每一列应用自定义函数。
    • axis=1 表示按行应用函数,axis=0 表示按列应用函数。
    • 适用于需要对每一行进行复杂操作的场景。

上一篇:python flatten

下一篇:python中set的用法

大家都在看

python 二维码识别

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

staticmethod在python中有

python 保存json文件

python的assert基本用法

python开发windows应用程序

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站