Python 使用掩码更改数组中的字符串

Python 使用掩码更改数组中的字符串,python,numpy,Python,Numpy,我有一个如下所示的数组: a = [['3','4','5','gg','5','6','7'], ['3','ww','6','7','4','2','3']] 是否有一种聪明的方法仅将非数字元素转换为0?如果它是嵌套的Pythonlist [list(map(lambda x:0 if type(x)== str else x,a1)) for a1 in a] Out[35]: [[3, 4, 5, 0, 5, 6, 7], [3, 0, 6, 7, 4, 2, 3]] 如果

我有一个如下所示的数组:

a = [['3','4','5','gg','5','6','7'],
     ['3','ww','6','7','4','2','3']]

是否有一种聪明的方法仅将非数字元素转换为0?

如果它是嵌套的Python
list

[list(map(lambda x:0 if type(x)== str else x,a1)) for a1 in a]
Out[35]: [[3, 4, 5, 0, 5, 6, 7], [3, 0, 6, 7, 4, 2, 3]]
如果是
np.array
既然你改变了你的问题

s = lambda x: x.isalpha()
func = np.vectorize(s)
a[func(a)]='0'
a=a.astype(int)
a
Out[55]: 
array([[3, 4, 5, 0, 5, 6, 7],
       [3, 0, 6, 7, 4, 2, 3]])

如果是嵌套的Python
list

[list(map(lambda x:0 if type(x)== str else x,a1)) for a1 in a]
Out[35]: [[3, 4, 5, 0, 5, 6, 7], [3, 0, 6, 7, 4, 2, 3]]
如果是
np.array
既然你改变了你的问题

s = lambda x: x.isalpha()
func = np.vectorize(s)
a[func(a)]='0'
a=a.astype(int)
a
Out[55]: 
array([[3, 4, 5, 0, 5, 6, 7],
       [3, 0, 6, 7, 4, 2, 3]])

numpy
有一种方法
np.core.defchararray.isdigit
用于检查字符串是否仅由数字组成

b = np.array([['3','4','5','gg','5','6','7'],
              ['3','ww','6','7','4','2','3']])

np.core.defchararray.isdigit(b)

Out: array([[ True,  True,  True, False,  True,  True,  True],
            [ True, False,  True,  True,  True,  True,  True]], dtype=bool)
将其与
np一起使用。其中
,将获得所需的输出

np.where(np.core.defchararray.isdigit(b), b, "0")

Out: array([['3', '4', '5', '0', '5', '6', '7'],
            ['3', '0', '6', '7', '4', '2', '3']], dtype='<U2')
np.where(np.core.defchararray.isdigit(b),b,“0”)
输出:数组(['3','4','5','0','5','6','7'],

[3',0',6',7',4',2',3']],dtype='
numpy
有一个方法
np.core.defchararray.isdigit
用于检查字符串是否仅由数字组成

b = np.array([['3','4','5','gg','5','6','7'],
              ['3','ww','6','7','4','2','3']])

np.core.defchararray.isdigit(b)

Out: array([[ True,  True,  True, False,  True,  True,  True],
            [ True, False,  True,  True,  True,  True,  True]], dtype=bool)
将其与
np一起使用。其中
,将获得所需的输出

np.where(np.core.defchararray.isdigit(b), b, "0")

Out: array([['3', '4', '5', '0', '5', '6', '7'],
            ['3', '0', '6', '7', '4', '2', '3']], dtype='<U2')
np.where(np.core.defchararray.isdigit(b),b,“0”)
输出:数组(['3','4','5','0','5','6','7'],

[3',0',6',7',4',2',3']],dtype='这实际上是一个NumPy数组吗?还是一个嵌套的Python列表?它是一个NumPy数组,它是
dtype
shape
?dtype=str,shape(7,7)数字是否大于9?这实际上是一个NumPy数组?还是一个嵌套的Python列表?这是一个NumPy数组,它是
dtype
shape
?dtype=str,shape(7,7)是大于9的数字?