如何在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[:, ...]<0is iterating over column labels of the boolean mask, not the actual data rows/values. - When you do
for j in df[i],jis just a copy of the value from the DataFrame—changingj = -5doesn'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:
| T1 | T2 | T3 | T4 |
|---|---|---|---|
| 20 | -5 | 4 | 3 |
| 85 | -5 | 34 | 21 |
| -5 | 22 | 31 | 75 |
| -5 | 5 | 7 | -5 |
内容的提问来源于stack exchange,提问作者hegdep

