np.数组不均匀数据(str+float)

2024-04-27 06:14:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从excel导入数据。矩阵是浮点(或可转换为浮点的字符串)和字符串的混合体,我需要对浮点进行操作,忽略字符串。如何将字符串设置为0?你知道吗

示例: 我有一个数组a: a=np.数组(['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)

Tags: 数据字符串incore示例fornprange
1条回答
网友
1楼 · 发布于 2024-04-27 06:14:55

下面是一种使用^{}^{}组合的方法-

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

样本运行-

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]])

相关问题 更多 >