Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 替换numpy ndarray中的值_Python_Arrays_Numpy_Dictionary - Fatal编程技术网

Python 替换numpy ndarray中的值

Python 替换numpy ndarray中的值,python,arrays,numpy,dictionary,Python,Arrays,Numpy,Dictionary,我有一个非常大的列表,其中包含numpy ndarray,我需要将字母映射到一个整数值 这与我认为可能有效的方法大致相同,但它似乎不能捕获所有数组 import numpy as np x = [np.array(['a','b','c']),np.array(['d','e']),np.array(['a','e'])] dict_x = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e':5} x[ x == 'a'] = dict_x.get('a') Outp

我有一个非常大的列表,其中包含numpy ndarray,我需要将字母映射到一个整数值

这与我认为可能有效的方法大致相同,但它似乎不能捕获所有数组

import numpy as np

x = [np.array(['a','b','c']),np.array(['d','e']),np.array(['a','e'])]
dict_x = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e':5}

x[ x == 'a'] = dict_x.get('a')

Output: [1, array(['d', 'e'], 
  dtype='<U1'), array(['a', 'e'], 
  dtype='<U1')]
但这又回来了,我想这是有道理的。有人有什么聪明的方法可以在所有情况下一次性替换所有这些值吗?非常感谢

[5, array(['d', 'e'], 
  dtype='<U1'), array(['a', 'e'], 
  dtype='<U1')]
您可以尝试以下方法:

x = [np.array(['a','b','c'], dtype="<U4"),np.array(['d','e'], dtype="<U4"),np.array(['a','e'], dtype="<U4")]
dict_x = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e':5}

for i in x:
    i[ i == 'a'] = dict_x.get('a')

x = array(['1', 'b', 'c'],
      dtype='<U1'), array(['d', 'e'],
      dtype='<U1'), array(['1', 'e'],
      dtype='<U1')]

是的,没错。我只是做了一个循环,将字典中的所有键作为一个外循环进行循环,然后将您的键作为一个内循环,其中包含一个变量,表示“a”的位置。我希望用一枪取代所有的,但我认为应该还是开着,所以我想不会有什么伤害,对吧?谢谢我刚刚发现这会将数字截断为一位数。因此,1000被读入为1。有什么想法吗?因为数组的数据类型是'
x = [np.array(['a','b','c'], dtype="<U4"),np.array(['d','e'], dtype="<U4"),np.array(['a','e'], dtype="<U4")]
dict_x = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e':5}

for i in x:
    i[ i == 'a'] = dict_x.get('a')

x = array(['1', 'b', 'c'],
      dtype='<U1'), array(['d', 'e'],
      dtype='<U1'), array(['1', 'e'],
      dtype='<U1')]