You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中遍历DataFrame并按指定列名输出指定格式内容

解决方案:循环DataFrame并按指定格式输出

以下是几种通过指定station和count列名实现需求的方法:

方法1:使用iterrows()逐行迭代

iterrows()会返回每行的索引与行数据对象,直接通过列名即可提取对应值:

import pandas as pd

# 构建示例DataFrame
df = pd.DataFrame({
    'id': [1, 2, 3, 4],
    'station': ['CL5', 'CL8', 'CL12', 'CL15'],
    'count': [5, 10, 4, 9]
})

# 循环遍历并输出指定格式内容
for _, row in df.iterrows():
    print(f"Station {row['station']} has {row['count']} results")

方法2:使用itertuples()(效率优先)

itertuples()返回命名元组,可通过列名对应的属性取值,迭代性能优于iterrows(),适合大数据量场景:

for row in df.itertuples():
    print(f"Station {row.station} has {row.count} results")

方法3:使用apply()函数

通过apply()对每行执行自定义逻辑,同样基于列名取值:

def print_station_data(row):
    print(f"Station {row['station']} has {row['count']} results")

df.apply(print_station_data, axis=1)

内容的提问来源于stack exchange,提问作者Julien

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 07:52:37