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

Python Pandas:基于含Time的列与Temp列求和更新同名列的问题

在Pandas中批量更新含特定字符串的列

问题说明

需要对DataFrame中所有列名包含Time的列,将列内每个元素与Temp列对应位置的元素求和,并用结果覆盖原列。现有代码仅能处理单列场景,无法适配多列情况。

原始受限代码

data={'Run_Time':[60,20,30,45,70,100],'Temp':[10,20,30,50,60,100], 'Rest_Time':[5,5,5,5,5,5]}
df=pd.DataFrame(data)

Pax_cols = [col for col in df.columns if 'Time' in col]
df[Pax_cols[0]]= df[Pax_cols[0]] + df["Temp"]

修正后的多列兼容代码

利用Pandas的批量列操作特性,直接对筛选出的列列表执行运算即可:

data={'Run_Time':[60,20,30,45,70,100],'Temp':[10,20,30,50,60,100], 'Rest_Time':[5,5,5,5,5,5]}
df=pd.DataFrame(data)

Pax_cols = [col for col in df.columns if 'Time' in col]
# 批量更新所有符合条件的列
df[Pax_cols] += df["Temp"]

print(df)

执行结果

得到的DataFrame数据如下:

data={'Run_Time':[70,40,60,95,130,200],'Temp':[10,20,30,50,60,100], 'Rest_Time':[15,25,35,55,65,105]}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 22:18:21