I am trying to speed up one of my functions. I have read that 'vectorization' is the fastest way to run these types of operations in Pandas, but how is this (or anything else faster) achievable with this code:
Dummy data
a = pd.DataFrame({'var1' : [33, 75, 464, 88, 34], 'imp_flag' : [1, 0, 0, 1, 1], 'donor_index' : [3, np.nan, np.nan, 4, 0]})
>>> a
var1 imp_flag donor_index
0 33 1 3.0
1 75 0 NaN
2 464 0 NaN
3 88 1 4.0
4 34 1 0.0
The operation in question
for index, row in a[a['imp_flag'] == 1].iterrows():
new_row = a[a.index == row.donor_index]
b = b.append(new_row)
Expected output
>>> b
var1 imp_flag donor_index
1 75 0 NaN
1 75 0 NaN
2 464 0 NaN