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

如何使用Python将NumPy数组中的负值替换为0

Replace Negative Values in a NumPy Array with 0

Hey there, let's sort this out for you! Replacing negative values in a NumPy array with 0 is super straightforward, and there are a couple of efficient ways to do it depending on whether you want to modify the original array or keep it intact.

Method 1: Modify the Original Array with Boolean Indexing

This is the most direct approach if you don't need to preserve the original array:

import numpy as np

# Define your input array
a = np.array([12, 12, 123, 4, -4, 0.15, -100])

# Replace all negative values with 0
a[a < 0] = 0

print(a)
# Output: [  12.    12.   123.     4.     0.     0.15   0.  ]

How this works: a < 0 creates a boolean array that flags every position where the element is negative. We use this boolean array to index into the original array and set those flagged positions to 0. It leverages NumPy's vectorized operations, which is way faster than looping through elements manually.

Method 2: Create a New Array with np.where

If you want to keep the original array untouched and generate a new modified array, use np.where:

import numpy as np

a = np.array([12, 12, 123, 4, -4, 0.15, -100])

# Generate a new array where negatives are replaced by 0
new_a = np.where(a < 0, 0, a)

print(new_a)
# Output: [  12.    12.   123.     4.     0.     0.15   0.  ]

The np.where function takes three arguments: a condition, the value to use when the condition is true, and the value to use when it's false. Here, we check if each element is negative—if yes, we use 0; otherwise, we keep the original element.

Either method will give you exactly the output you're aiming for!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 06:23:13