我有两个numpy数组,A和B. A包含dtypes = ['ID','Value','Type'],B包含dtypes = ['ID','Value']。
基本上我想用A中的值替换A中的'Value',但仅用于'两者中的ID'(所以B中的ID也在A中)。
A = array([[1,2,3,4,5,6,7],[0.785, 0.985, 0.8562, 0.9652, 0.664, 0.962, 0.872],['sio', 'sco', 'sio', 'sco', 'sio', 'sco', 'sio']])
B = array([[1,2,3],[0.85,0.4585,0.8436]])
A和B的长度可能在大小上不同,因此需要映射值而不是假设id都是相同的顺序。
这样做的最快方法是什么?
答案 0 :(得分:1)
希望这会有所帮助,我使用了OrderedDict
,以防您的数据不仅仅是有序的:
from collections import OrderedDict
A = [[1,2,3,4,5,6,7],[0.785,0.985,0.8562,0.9652,0.664,0.962,0.872],[' sio', 'sco', 'sio', 'sco', 'sio', 'sco','sio']]
B = [[1,2,3],[0.85,0.4585,0.8436]]
a = OrderedDict(zip(*A[:2]))
b = dict(zip(*B))
c = OrderedDict([(k, b[k] if k in b else v) for k, v in a.items()])
A = [c.keys(), c.values(), A[2]]
输出:
[[1, 2, 3, 4, 5, 6, 7],
[0.85, 0.4585, 0.8436, 0.9652, 0.664, 0.962, 0.872],
[' sio', 'sco', 'sio', 'sco', 'sio', 'sco', 'sio']]
答案 1 :(得分:0)
这对你来说足够快吗?
import numpy
A = numpy.array([[1,2,3,4,5,6,7],[0.785,0.985,0.8562,0.9652,0.664,0.962,0.872],[' sio', 'sco', 'sio', 'sco', 'sio', 'sco','sio']])
B = numpy.array([[1,2,3],[0.85,0.4585,0.8436]])
for i, x in enumerate(A[0]):
if x in str(B[0]):
A[1,i] = B[1,i]
print A
输出继电器:
[['1' '2' '3' '4' '5' '6' '7']
['0.85' '0.4585' '0.8436' '0.9652' '0.664' '0.962' '0.872']
[' sio' 'sco' 'sio' 'sco' 'sio' 'sco' 'sio']]