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

如何在Pandas中替换DataFrame连续四列的负值为指定值?

Hey there! Let's fix this problem properly—Pandas is designed to avoid those messy nested loops, so we can do this way more cleanly.

最简洁的Pandas原生方法

First, target the specific columns you care about (T1 to T4) and use either mask() or where() to replace negative values in one line:

Using mask()

This replaces values where the condition is True (i.e., values < 0) with your desired value (-5):

# Define the columns we want to modify
target_cols = ['T1', 'T2', 'T3', 'T4']
# Replace negatives with -5
df[target_cols] = df[target_cols].mask(df[target_cols] < 0, -5)

Using where()

This does the opposite: keeps values where the condition is True (values >= 0), and replaces the rest with -5:

df[target_cols] = df[target_cols].where(df[target_cols] >= 0, -5)

Alternative: Using applymap()

If you prefer a more explicit function-based approach, applymap() works too (great for custom logic if you ever need it):

df[target_cols] = df[target_cols].applymap(lambda x: -5 if x < 0 else x)

Why your original code didn't work

Let's break down the issues with your loop approach:

  • Your outer loop for i in df.iloc[:, ...]<0 is iterating over column labels of the boolean mask, not the actual data rows/values.
  • When you do for j in df[i], j is just a copy of the value from the DataFrame—changing j = -5 doesn't modify the original DataFrame at all (you're not updating the actual cells).
  • Nested loops are inefficient in Pandas, especially with larger datasets—vectorized operations (like the methods above) are way faster and more readable.

Result after running the code

Your DataFrame will look like this:

T1T2T3T4
20-543
85-53421
-5223175
-557-5

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:35:01