You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
returns: full (n x n) Euclidean distance matrix as numpy array
122
+
"""
123
+
X = np.asarray(mat, dtype=float)
124
+
125
+
# upper triangle (condensed form)
126
+
upper = pdist(X, metric="euclidean")
127
+
128
+
# convert to full symmetric matrix
129
+
D = squareform(upper)
130
+
131
+
return D
132
+
```
133
+
134
+
I am sure by now you can check the run time without my help.
135
+
136
+
95
137
# The key lesson
96
138
97
139
For numerical work:
98
140
99
141
✅ Prefer **built-in** pandas/NumPy methods
100
142
❌ Avoid Python loops over rows/columns
101
143
144
+
If not 100% sure you know all about the possible libraries you could use I recommend asking an AI tool for the max speed up in your function.
145
+
102
146
---
103
147
104
148
# What about pandas apply?
105
149
106
150
In R, `apply()` can be a speed trick.
107
151
In Python, `DataFrame.apply()` usually still runs a Python function once per row/column.
108
152
109
-
That means it often behaves like a loop (and can be slow).
110
-
111
-
Example task:
153
+
That means it often behaves like a loop (and can be slow). But eucledian distance is probably the worst example for apply as it works on one row/column only.
154
+
So for this we switch to a simple mean calculation.
0 commit comments