简体   繁体   English

用 Python 中的数字替换所有非零元素

[英]Replacing all non-zero elements with a number in Python

I want to replace all non-zero elements of the array X with 10 .我想用10替换数组X的所有非零元素。 Is there a one-step way to do so?有没有一步一步的方法呢? I present the expected output.我提出了预期的 output。

import numpy as np
X=np.array([[10.                 ,  0.6382821834929432 ,  0.5928417218382795 ,
        0.5542698411479658 ,  0.                 ,  0.6677634679746701 ,
        0.8578897621707481 ,  0.                 ,  0.6544597670890333 ,
        0.32706383813570833,  0.                 ,  0.8966468940380192 ]])

The expected output is预期的 output 是

X=array([[10.,  10. ,  10. ,
        10. ,  0.,  10.,
        10. ,  0.,  10.,
        10.,  0.,  10. ]])

Use numpy.where :使用numpy.where

X2 = np.where(X!=0, 10, 0)

Or, for in place modification:或者,对于就地修改:

X[X!=0] = 10

For fun, a variant using equivalence of True/False and 1/0:为了好玩,使用 True/False 和 1/0 等价的变体:

X2 = (X!=0)*10

Output: Output:

array([[10, 10, 10, 10,  0, 10, 10,  0, 10, 10,  0, 10]])

You can consider using numpy.putmask您可以考虑使用numpy.putmask

Here is an example for your solution这是您的解决方案的示例

import numpy as np

X=np.array([[10.                 ,  0.6382821834929432 ,  0.5928417218382795 ,
        0.5542698411479658 ,  0.                 ,  0.6677634679746701 ,
        0.8578897621707481 ,  0.                 ,  0.6544597670890333 ,
        0.32706383813570833,  0.                 ,  0.8966468940380192 ]])

np.putmask(X, X != 0, 10)

X[X.=0]=10.0 this will works for you X[X.=0]=10.0 这对你有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM