Skip to main content
 首页 » 编程设计

python之np.array with inhomogeneos data (str+float)

2025年05月04日14jpfss

我正在从 excel 导入数据。矩阵是 float (或可转换为 float 的字符串)和字符串的混合体,我需要对 float 进行运算,而忽略字符串。如何将字符串设置为 0?

例子: 我有一个数组: a = np.array(['1','.5','day'],['month','.5','7.3'])

我想将该数组转换为: a = ([1,.5,0],[0,.5,7.3])

编辑: 它使用以下代码对我有用:

shape = np.shape(a) 
for i in range(shape[0]): 
    for j in range(shape[1]): 
        if np.core.defchararray.isdigit((np.core.defchararray.replace(a[i,j],'.','')))==False: 
            a[i,j]=0 
 
a=np.array(a,float) 

请您参考如下方法:

这是使用 np.core.defchararray.replace 组合的一种方法和 np.core.defchararray.isdigit -

a[~np.core.defchararray.isdigit(np.core.defchararray.replace(a,'.',''))]=0 
out = a.astype(float) 

sample 运行-

In [2]: a 
Out[2]:  
array([['1', '.5', 'day'], 
       ['month', '.5', '7.3']],  
      dtype='|S5') 
 
In [3]: a[~np.core.defchararray.isdigit(np.core.defchararray.replace(a,'.',''))] = 0 
 
In [4]: a.astype(float) 
Out[4]:  
array([[ 1. ,  0.5,  0. ], 
       [ 0. ,  0.5,  7.3]])