Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a loop over pandas DataFrame

I am iterating through a pandas dataframe (df) and adding scores to a dictionary containing python lists (scores):

for index, row in df.iterrows():
    scores[row["key"]][row["pos"]] = scores[row["key"]][row["pos"]] + row["score"]

The scores dictionary initially is not empty. The dataframe is very large and this loop takes a long time. Is there a way to do this without a loop or speed it up in some other way?

like image 454
Jumee Avatar asked Sep 14 '26 10:09

Jumee


1 Answers

A for loop seems somewhat inevitable, but we can speed things up with NumPy's fancy indexing and Pandas' groupby:

# group the scores over `key` and gather them in a list
grouped_scores = df.groupby("key").agg(list)

# for each key, value in the dictionary...
for key, val in scores.items():
    
    # first lookup the positions to update and the corresponding scores
    pos, score = grouped_scores.loc[key, ["pos", "score"]]

    # then fancy indexing with `pos`: reaching all positions at once
    scores[key][pos] += score
like image 161
Mustafa Aydın Avatar answered Sep 17 '26 00:09

Mustafa Aydın



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!