Ealtuntas
Ealtuntas

Reputation: 3

Sum values in given Index order consecutively in pandas dataframe

I have a list of index values that represent the order of the coordinates I should be visiting on a map. Each index represents (x,y).

Out[4]: [0, 8, 11, 6 ,10, 3, 4, 2, 14, 1, 7, 12, 13, 15, 5, 9]

Using these coordinates I generated a distance matrix. My aim is to find the total travel distance.

I manage to achieve it using iloc where I consecutively summed the index values. However need an automated way of doing this as I have a large amount of data to go through. Is there an easier way to do this?

In[6]: dmatrix.iloc[0][8]+dmatrix.iloc[8][11]+dmatrix.iloc[11][6]+dmatrix.iloc[6][10]+dmatrix.iloc[10][3]+dmatrix.iloc[3][4]+dmatrix.iloc[4][2]+dmatrix.iloc[2][14]+dmatrix.iloc[14][1]+dmatrix.iloc[1][7]+dmatrix.iloc[7][12]+dmatrix.iloc[12][13]+dmatrix.iloc[13][15]+dmatrix.iloc[15][5]+dmatrix.iloc[5][9]+dmatrix.iloc[9][0]

Upvotes: 0

Views: 51

Answers (1)

Maxouille
Maxouille

Reputation: 2911

You can create a loop and iterate through your list of indexes:

sum = 0
for i in range(0, len(yourList)-1):
    sum += dmatrix.iloc[yourList[i]][yourList[i+1]]

Best

Upvotes: 1

Related Questions