I am working on a small task in which I have to find the distance between two nodes. Each node has X and Y coordinates which can be seen below.
node_number X_coordinate Y_coordinate
0 0 1 0
1 1 1 1
2 2 1 2
3 3 1 3
4 4 0 3
5 5 0 4
6 6 1 4
7 7 2 4
8 8 3 4
9 9 4 4
10 10 4 3
11 11 3 3
12 12 2 3
13 13 2 2
14 14 2 1
15 15 2 0
For the purpose I mentioned above, I wrote below code,
X1_coordinate = df['X_coordinate'].tolist()
Y1_coordinate = df['Y_coordinate'].tolist()
node_number1 = df['node_number'].tolist()
nodal_dist = []
i = 0
for i in range(len(node_number1)):
dist = math.sqrt((X1_coordinate[i 1] - X1_coordinate[i])**2 (Y1_coordinate[i 1] - Y1_coordinate[i])**2)
nodal_dist.append(dist)
I got the error
list index out of range
Kindly let me know what I am doing wrong and what should I change to get the answer.
CodePudding user response:
Indexing starts at zero, so the last element in the list has an index that is one less than the number of elements in that list. But the len()
function gives you the number of elements in the list (in other words, it starts counting at 1), so you want the range of your loop to be len(node_number1) - 1
to avoid an -off-by-one error.
CodePudding user response:
The problems should been in this line
dist = math.sqrt((X1_coordinate[i 1] - X1_coordinate[i])**2 (Y1_coordinate[i 1] - Y1_coordinate[i])**2)
the X1_coordinate[i 1]
and the ] Y1_coordinate[i 1]]
go out of range on the last number call.
CodePudding user response:
When your data is in pandas
. Sometimes you can do what you want without for-loop
and use vectorize functional. For your problem you can use pandas.shift()
and numpy.sqrt()
.
import numpy as np
x_shift = df['X_coordinate'].shift(-1)
y_shift = df['Y_coordinate'].shift(-1)
nodal_dist = np.sqrt((x_shift - df['X_coordinate'])**2 (y_shift - df['Y_coordinate'])**2).dropna().to_list()