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

Python中如何高效创建DataFrame新列并通过自定义函数填充值

问题原因

你之前的写法每次循环都给整个price列重新赋值,因此循环结束后整列只会保留最后一次计算得到的价格值。

推荐解决方案(性能最优)

直接使用pandas的apply按行处理,不需要手动写循环,代码更简洁效率更高:

CAR['price'] = CAR.apply(lambda row: calculate_price((row['car_model'], row['year'])), axis=1)

注:axis=1表示按行遍历,每一行的car_model和year会被包装成元组传入自定义函数,返回结果会自动对应到当前行的price列。

原循环写法的修正方案

如果你需要保留原有循环逻辑,需要通过行索引给对应位置单独赋值,修改后代码如下:

# 方式1:基于原numpy遍历逻辑修改(适配索引为默认0开始连续整数的DataFrame)
model_year = CAR[["car_model", "year"]]
for idx, x in enumerate(model_year.to_numpy()):
    model_year_tuple = tuple(x)
    price = calculate_price(model_year_tuple)
    # 给索引为idx的行的price列单独赋值
    CAR.loc[idx, 'price'] = price

# 方式2:使用iterrows遍历(适配任意索引格式的DataFrame)
for idx, row in CAR.iterrows():
    model_year_tuple = (row['car_model'], row['year'])
    price = calculate_price(model_year_tuple)
    CAR.loc[idx, 'price'] = price

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 07:36:03