用另一个NumPy数组中的值替换一个NumPy数组中的值

4
我有一个1000 * 1000的numpy数组,包含一百万个值,是按照以下方式创建的:
>>import numpy as np
>>data = np.loadtxt('space_data.txt')
>> print (data)
>>[[ 13.  15.  15. ...,  15.  15.  16.]
   [ 14.  13.  14. ...,  13.  15.  16.]
   [ 16.  13.  13. ...,  13.  15.  17.]
   ..., 
   [ 14.   15.  14. ...,  14.  14.  13.]
   [ 15.   15.  16. ...,  16.  15.  14.]
   [ 14.   13.  16. ...,  16.  16.  16.]]

我有另一个NumPy数组,其中有2列,如下所示:
>> print(key)
>>[[ 10.,   S],
   [ 11.,   S],
   [ 12.,   S],
   [ 13.,   M],
   [ 14.,   L],
   [ 15.,   S],
   [ 16.,   S],
   ...,
   [ 92.,   XL],
   [ 93.,   M],
   [ 94.,   XL],
   [ 95.,   S]]

我想要的基本上是将数据数组中的每个元素替换为密钥数组第二列中对应的元素,就像这样...
>> print(data)
>>[[ M  S  S ...,  S  S  S]
   [ L   M  L ...,  M  S  S]
   [ S   M  M ...,  M  S  XL]
   ..., 
   [ L   S  L ...,  L  L  M]
   [ S   S  S ...,  S  S  L]
   [ L   M  S ...,  S  S  S]]

请修正您的代码片段中的 data,因为它是错误的(缺少逗号)。这可能会让其他数据类型的用户感到困惑。 - ha9u63a7
1
S、M、L是变量名还是字符串? - Julien Spronck
如果数据是一个浮点数的numpy数组,你不能用字符串替换它的元素,所以你需要创建另一个列表。 - Julien Spronck
@ha9u63ar..我直接从终端复制了这个..我打印了数组,但没有逗号.. - Amistad
@Amistad 还要发布 NumPy 数组的 repr 版本:print(repr(data)) - Ashwini Chaudhary
@ Julien..我会编辑问题..让S=1,M=2,L=3和XL=4..这样有办法吗? - Amistad
4个回答

9

在Python中,字典是从键到值的自然选择。NumPy没有直接相当于字典的数据结构。但是它有数组,可以进行快速的整数索引。例如,

In [153]: keyarray = np.array(['S','M','L','XL'])

In [158]: data = np.array([[0,2,1], [1,3,2]])

In [159]: keyarray[data]
Out[159]: 
array([['S', 'L', 'M'],
       ['M', 'XL', 'L']], 
      dtype='|S2')

因此,如果我们能够将您的key数组转换成以下形式:

In [161]: keyarray
Out[161]: 
array(['', '', '', '', '', '', '', '', '', '', 'S', 'S', 'S', 'M', 'L',
       'S', 'S', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
       '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
       '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
       '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
       '', '', '', '', '', '', '', '', '', '', 'XL', 'M', 'XL', 'S'], 
      dtype='|S32')

因此,使得数字10对应字母'S'的意思是keyarray[10]等于S,以此类推:

In [162]: keyarray[10]
Out[162]: 'S'

然后我们可以使用 keyarray[data] 来得到所需的结果。


import numpy as np

data = np.array( [[ 13.,   15.,  15.,  15.,  15.,  16.],
                  [ 14.,   13.,  14.,  13.,  15.,  16.],
                  [ 16.,   13.,  13.,  13.,  15.,  17.],
                  [ 14.,   15.,  14.,  14.,  14.,  13.],
                  [ 15.,   15 ,  16.,  16.,  15.,  14.],
                  [ 14.,   13.,  16.,  16.,  16.,  16.]])

key = np.array([[ 10., 'S'],
                [ 11., 'S'],
                [ 12., 'S'],
                [ 13., 'M'],
                [ 14., 'L'],
                [ 15., 'S'],
                [ 16., 'S'],
                [ 17., 'XL'],
                [ 92., 'XL'],
                [ 93., 'M'],
                [ 94., 'XL'],
                [ 95., 'S']])

idx = np.array(key[:,0], dtype=float).astype(int)
n = idx.max()+1
keyarray = np.empty(n, dtype=key[:,1].dtype)
keyarray[:] = ''
keyarray[idx] = key[:,1]

data = data.astype('int')
print(keyarray[data])

产量
[['M' 'S' 'S' 'S' 'S' 'S']
 ['L' 'M' 'L' 'M' 'S' 'S']
 ['S' 'M' 'M' 'M' 'S' 'XL']
 ['L' 'S' 'L' 'L' 'L' 'M']
 ['S' 'S' 'S' 'S' 'S' 'L']
 ['L' 'M' 'S' 'S' 'S' 'S']]

请注意,data = data.astype('int') 假定 data 中的浮点数可以唯一地映射到整数。这似乎适用于您的数据,但对于任意浮点数来说并非如此。例如,astype('int') 会将1.0和1.5都映射到1。
In [167]: np.array([1.0, 1.5]).astype('int')
Out[167]: array([1, 1])

3
一个未向量化的线性方法将会在这里使用一个字典:
dct = dict(keys)
# new array is required if dtype is different or it it cannot be casted
new_array = np.empty(data.shape, dtype=str)
for index in np.arange(data.size):
    index = np.unravel_index(index, data.shape)
    new_array[index] = dct[data[index]] 

2
import numpy as np

data = np.array([[ 13.,  15.,  15.],
   [ 14.,  13.,  14. ],
   [ 16.,  13.,  13. ]])

key = [[ 10.,   'S'],
   [ 11.,   'S'],
   [ 12.,   'S'],
   [ 13.,   'M'],
   [ 14.,   'L'],
   [ 15.,   'S'],
   [ 16.,   'S']]

data2 = np.zeros(data.shape, dtype=str)

for k in key:
    data2[data == k[0]] = k[1]

如果 key 数组中的元素数量不大,那么这应该足够快。但是如果 key 的大小增加,它将变成二次方速度。 - Ashwini Chaudhary
看起来在键“maybe”中应该有86个条目...否则可能是最快的。 - Julien Spronck

0
# Create a dataframe out of your 'data' array and make a dictionary out of your 'key' array. 
import numpy as np
import pandas as pd

data = np.array([[ 13.,  15.,  15.],
               [ 14.,  13.,  14. ],
               [ 16.,  13.,  13. ]])
data_df = pd.DataFrame(data)
key  = dict({10 : 'S',11 : 'S', 12 : 'S', 13 : 'M',14:'L',15:'S',16:'S'})
# Replace the values in newly created dataframe and convert that into array.
data_df.replace(key,inplace = True)

data = np.array(data_df)
print(data)

这将是输出结果:
[['M' 'S' 'S']
['L' 'M' 'L']
['S' 'M' 'M']]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接