【发布时间】:2021-01-12 14:20:50
【问题描述】:
我有 3 个数组
a = np.array([[1], [4], [5], [11], [7]])
b = np.array([[14], [3], [2], [10], [12]])
c = np.array([[6], [13], [15], [8], [9]])
我想在每一行中合并和排序它们以获得:
[[ 1 6 14]
[ 3 4 13]
[ 2 5 15]
[ 8 10 11]
[ 7 9 12]]
并查看从哪个初始数组 (a,b,c) 中选取每个值。所以,我使用了这段代码:
combined = np.concatenate([a, b, c], axis=1)
names = np.array(['a','b','c'])
L = names[np.argsort(combined)]
它给了我这个结果:
[['a' 'c' 'b']
['b' 'a' 'c']
['b' 'a' 'c']
['c' 'b' 'a']
['a' 'c' 'b']]
我还有一本字典:
Test = np.array(range(101,116)).reshape((5,3), order = 'F')
或
[[101 106 111]
[102 107 112]
[103 108 113]
[104 109 114]
[105 110 115]]
Dic = {'a':Test[:,0], 'b':Test[:,1], 'c':Test[:,2]}
现在我希望使用以下方法将 Dic 与 L 关联起来:
new = []
for i in range(0,3):
for j in range(0,5):
if L[j,i]=='a':
H = Dic['a'][j]
elif L[j,i]=='b':
H = Dic['b'][j]
elif L[j,i]=='c':
H = Dic['c'][j]
new = np.append(new, H)
final = new.reshape((5,3), order = 'F')
给我最终的结果:
[[101. 111. 106.]
[107. 102. 112.]
[108. 103. 113.]
[114. 109. 104.]
[105. 115. 110.]]
但是,对于我非常大的真实数据集,这个过程需要几个小时。我正在寻找一种更好的方法来加速我的代码。
换句话说,我正在根据第一个数组对第二个数组进行排序。
first array:[['a' 'c' 'b']
['b' 'a' 'c']
['b' 'a' 'c']
['c' 'b' 'a']
['a' 'c' 'b']]
second array: [[101 106 111]
[102 107 112]
[103 108 113]
[104 109 114]
[105 110 115]]
第1、2、3列分别对应'a'、'b'、'c'
【问题讨论】:
标签: python numpy dictionary