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

能否通过遍历pandas DataFrame的f列生成temperature列?实现方法?

解答

遍历是否可行?

可行,但非常不推荐——pandas天生适合向量化操作,遍历循环的效率极低,数据量越大差距越明显。不过如果只是要实现逻辑,遍历代码也能完成需求。

遍历实现代码

假设你的原DataFrame名为df,可以用以下两种遍历方式:

方式1:用iterrows()逐行遍历

import pandas as pd

# 初始化空列表存储新数据
new_rows = []
# 遍历原DataFrame的每一行
for _, row in df.iterrows():
    # 根据f的值判断温度标签
    temp_label = 'hot' if row['f'] == 0 else 'cold'
    # 把当前行的f和温度标签加入列表
    new_rows.append({'f': row['f'], 'temperature': temp_label})

# 把列表转为新的DataFrame
new_df = pd.DataFrame(new_rows)

方式2:用apply()行级遍历

# 定义一个根据行数据返回温度标签的函数
def get_temperature(row):
    return 'hot' if row['f'] == 0 else 'cold'

# 复制原DataFrame的f列作为新DataFrame的基础
new_df = df[['f']].copy()
# 对每一行应用函数生成temperature列
new_df['temperature'] = df.apply(get_temperature, axis=1)

推荐:更高效的向量化实现

如果你追求性能,直接用以下两种方法,速度比遍历快几个数量级:

方法1:字典映射(map())

# 定义f值到温度标签的映射字典
temp_mapping = {0: 'hot', 1: 'cold'}
# 复制f列并生成temperature列
new_df = df[['f']].copy()
new_df['temperature'] = df['f'].map(temp_mapping)

方法2:条件判断(np.where())

import numpy as np

new_df = df[['f']].copy()
# 用np.where做向量化条件判断
new_df['temperature'] = np.where(df['f'] == 0, 'hot', 'cold')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 01:45:38