0

I want to improve my Python and I'm curious if there's an elegant way to increment the index of arr in the loop without using integer x in this code:

def predict_one_instance(xSeriesTestVector, xTrainInstances, yTrainCategories, distanceMetric, k):

    distances = calc_distances(xSeriesTestVector, xTrainInstances,distanceMetric)
    sorted_distances = np.sort(distances)
    arr = np.zeros((k,), dtype=int)
    x = 0   
    for el in sorted_distances[:k]:
        arr[x] = yTrainCategories.iloc[np.where(distances == el)]
        x+=1
    return np.bincount(arr).argmax()
Tom S
  • 511
  • 1
  • 4
  • 19
  • Does this answer your question? [Accessing the index in 'for' loops?](https://stackoverflow.com/questions/522563/accessing-the-index-in-for-loops) – Chris Mar 28 '20 at 18:11

1 Answers1

2

Maybe you want to use enumerate?

for item in iterable:
    do_stuff(item)

can be turned to

for i, item in enumerate(iterable):
    do_stuff(item, i)

where i contains the index of item in the iterable.

So, in your example:

for x, el in enumerate(sorted_distances[:k]):
    arr[x] = yTrainCategories.iloc[np.where(distances == el)]

Although you might as well use the good old range if your iterable is a list:

for x in range(k):
    arr[x] = yTrainCategories.iloc[np.where(distances == sorted_distances[x])]

Piyush Singh
  • 2,736
  • 10
  • 26