我有这样的字典
{0: array([-6139.66579119, -8102.82498701, -8424.43378713, -8699.96492463,
-9411.35741859]),
1: array([ -7679.11144698, -16699.49166421, -3057.05148494, -10657.0539235 ,
-3091.04936367]),
2: array([ -7316.47405724, -15367.98445067, -6660.88963907, -9634.54357714,
-6667.05832509]),
3: array([-7609.14675848, -9894.14708559, -4040.51364199, -8661.16152946,
-4363.71589143]),
4: array([-5068.85919923, -6691.36104136, -6659.66791024, -6666.66570889,
-5365.35153533]),
5: array([ -8341.96211464, -13495.42783124, -4782.52084352, -10355.98002 ,
-5424.48813488]),
6: array([ -7740.36341878, -16165.48430318, -5169.42471878, -12369.79859385,
-5807.66380805]),
7: array([-10645.12432969, -5465.30533986, -6756.65159092, -4146.34937333,
-6765.69595854]),
8: array([ -7765.04423986, -11679.3889257 , -4218.9629257 , -6565.64225892,
-4538.09199979]),
9: array([-5869.18259848, -7809.21110907, -3272.33611955, -3881.64743889,
-3275.54657818])}
我想做的是:
比较每个数组中的第一个值,在这种情况下为-6139,-7649 ...并找到最大值(-5068),然后在列表中返回键4。
比较每个数组中的第二个值-8102,-16699 ...找到最大值并返回键,追加到列表中。
我该怎么做?
我的代码是这样的:
def预测(trainingData,testData):
pred = {}
maxLabel = None
prediction=[]
maxValue = -9999999999
pred = postProb(trainingData, testData)
for key, value in pred.items():
for i in range(value.shape[0]):
for j in range(10):
if pred[j][i] > maxValue:
maxValue = pred[key][i]
maxLabel = key
prediction.append(maxLabel)
return prediction
pred是字典。似乎没有必要进行第一个循环,但我需要它来遍历字典中的元素
答案 0 :(得分:0)
您可以使用numpy
数组的argmax
方法来获取所需的内容。
np.array(list(abc.values())).argmax(axis=0)
Out: array([4, 7, 1, 9, 1])
这仅在您的键是连续的整数(如您的示例)时才有效。如果您想要更简单的方法,可以使用pandas
。
import pandas as pd
df = pd.DataFrame(my_dict)
my_list = list(df.idxmax(axis=1))
print(my_list)
Out: [4, 7, 1, 9, 1]