SCB*_*SCB 2 python arrays dictionary numpy
我有一个2维numpy数组和一个字典,它将在数组第一列中找到的值映射到其他值.例如:
>>> x = np.array([[14, 4], [18, 2], [15, 7]])
>>> d = {5: 0, 7: 2, 14: 3, 15: 12, 16: 10, 18: 30}
Run Code Online (Sandbox Code Playgroud)
尽管第一列中的所有值都在d,x但不保证所有键都x在d.我想要做的是将第一列中的值替换x为相关值d.就像是:
>>> x[:, 0] = d[x[:, 0]]
Run Code Online (Sandbox Code Playgroud)
所以新的数组将是:
>>> x
array([[3, 4], [30, 2], [12, 7]])
Run Code Online (Sandbox Code Playgroud)
当然,这不起作用,因为我基本上只是将整个数组传递到想要键的字典中.我提出的最好的是使用for循环:
>>> for i in range(x.shape[0]):
... x[i, 1] = d[x[i, 1]]
Run Code Online (Sandbox Code Playgroud)
这当然是非常不合理的,可能效率不高.我的问题是,做这样的事情有一种"笨拙的方式"吗?
这是一个Numpythonic解决方案 -
# Extract values and keys
dv = np.array(list(d.values()))
dk = np.array(list(d.keys()))
# Get positions of keys in first column of x and thus change the first column
_,C = np.where(x[:,0][:,None] == dk)
x[:,0] = dv[C]
Run Code Online (Sandbox Code Playgroud)
样品运行 -
In [107]: x
Out[107]:
array([[15, 4],
[18, 2],
[14, 7]])
In [108]: d
Out[108]: {16: 10, 18: 3, 5: 0, 7: 2, 14: 12, 15: 30}
In [109]: # Extract values and keys
...: dv = np.array(list(d.values()))
...: dk = np.array(list(d.keys()))
...:
...: # Get positions of keys in first column of x and thus change the first column
...: _,C = np.where(x[:,0][:,None] == dk)
...: x[:,0] = dv[C]
...:
In [110]: x
Out[110]:
array([[30, 4],
[ 3, 2],
[12, 7]])
Run Code Online (Sandbox Code Playgroud)