在单元格中搜索并替换字符串

时间:2018-06-19 09:51:03

标签: python string python-3.x numpy

我有电压测量的行值。

-Infinity,
0.00061050,
0.00061050,
-Infinity,
0.00061050,
-Infinity,
-Infinity,
0.00061050,
0.00122100,
Infinity,
Infinity,
Infinity,
Infinity,

我只需要" Infinity"换成1

实际上numpy会将"+/-Infinity"转换为-infinf

> import matplotlib.pyplot as plt 
> import numpy as np
> 
> x, y, z =
> np.loadtxt('20180618-0001_innen_aussen_innen_0_25_Sek_Abtast.csv',
> delimiter=',', skiprows=10, unpack=True)

> 
> z[z == '-inf'] = 1
> 
> print(z) plt.plot(x,y,z, label='Loaded from file!')        
>
> plt.xlabel('x')
>
> plt.ylabel('y')
>
> plt.title('Interesting Graph\nCheck it out')
>
> plt.legend() 
>
> plt.show()

2 个答案:

答案 0 :(得分:3)

创建一个布尔掩码来索引数组并应用操作(将掩码值设置为1):

z[np.abs(z) == np.inf] = 1

感谢SashaTsukanov指出你也可以使用:

z[np.isinf(z)] = 1

如果您想根据正面或负面znp.inf数组设置单独的值:

# create some random test data:
z = np.random.rand(10)
z[4] = -np.inf
z[8] = np.inf
# apply it:
z[z == -np.inf] = 0
z[z == np.inf] = 1
print(z)  # print it
# out: [0.15883998, 0.16284797, 0.3730809, 0.37536173, 0., 0.41195883, 0.39620129, 0.74374664, 1., 0.87745629]

如果这对您的肯定np.inf不起作用,请尝试以下操作:

z[z == -np.inf] = 0
z[np.isinf(z)] = 1

答案 1 :(得分:0)

-inf受到影响

使用z[ ==np.inf] = 1根本不执行inf

import matplotlib.pyplot as plt
import numpy as np

x, y, z = np.loadtxt('20180618-0001_innen_aussen_innen_0_25_Sek_Abtast.csv', delimiter=',', skiprows=10, unpack=True)




z[z == np.inf] = 1
z[z == -np.inf]= 0


for row in z:
    print(row)