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
@@ -164,70 +189,25 @@ If not 100% sure you know all about the possible libraries you could use I recom
164
189
165
190
---
166
191
167
-
# What about pandas apply?
168
-
169
-
In R, `apply()` can be a speed trick.
170
-
In Python, `DataFrame.apply()` usually still runs a Python function once per row/column.
171
-
172
-
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.
173
-
So for this we switch to a simple mean calculation.
This is rather fast, but using the inbuild pandas mean function is even faster:
186
-
187
-
188
-
```python
189
-
(_, t_vec) = timed( hspc_data.mean, axis=1)
190
-
print("pandas time:", t_vec)
191
-
```
192
-
193
-
If we would have our data as a numpy array instead we could get this even faster using numpy's vectorization:
194
-
195
-
196
-
```python
197
-
arr = np.array(hspc_data)
198
-
(c, t_fast) = timed(arr.mean, axis=1 )
199
-
print("numpy:", t_fast)
200
-
```
201
-
202
-
**Take Home** If numpy has a function for your problem use that!
203
-
204
-
---
205
192
206
193
# Interpreting the result
207
194
208
195
Usually:
209
196
210
197
- vectorized version is very fast
211
-
- apply is much slower
212
-
213
-
Why? Because `apply` calls Python code repeatedly.
214
-
215
-
---
216
-
217
-
# When is apply OK?
218
-
219
-
`apply` can be reasonable when:
198
+
- pure python as well as manual for loops are much slower
220
199
221
-
- there is no clean vectorized solution
222
-
- the dataset is small
223
-
- readability matters more than speed
200
+
Why? Because even a for loop calls Python code repeatedly whereas the vectorized function (c or fortran) works on one big memory block.
224
201
225
-
But for large biological matrices (genes x samples), prefer vectorization.
226
202
227
203
---
228
204
229
205
# Exercise
230
206
231
-
Just keep the ``timed`` function and apply it later on whenever you like ;-)
207
+
Take the function ``zscore_rows`` and convert it from using a numpy ndarray to using our own data structure.
208
+
While doing that change tha action to modifying the data in place.
209
+
210
+
**Note:** Mutable objects (like lists, dictionaries, and arrays) can be changed inside a function, while immutable objects (like numbers and strings) cannot. Think of it like "Small objects like numbers or strings can be copied, but putatively large ones like matrices or dictionaries should not be copied".
211
+
232
212
233
213
In the next section, we will apply these ideas to real expression data: selecting variable genes and scaling (z-scores).
0 commit comments