Marco Pistilli
Marco Pistilli

Reputation: 1

Python does not update dataframe while iterating over rows

I don't get why python won't update my dataframe object: The code snippet is this:

for index, row in df.iterrows():
   t = df.loc[index, :"score"]
   b = [float(i) for i in t if i != 's']
   m = sum(b)/len(b)

   df.at[index, "score"] = m

   print(df.at[index, "score"]) # Does not print out m, it prints out 0, the default value

The thing that this snippet should do is get all the values in a row, compute the average and then add this average to the dataframe.

Upvotes: 0

Views: 43

Answers (1)

Jondiedoop
Jondiedoop

Reputation: 3353

Iterating over rows in a DataFrame is very seldomly the way to go. Instead, use
df.loc[:, :'score'].mean('columns')
which is more readable and much faster.

To answer your question directly (why your way doesn't work) we would need more information (see comments).

Upvotes: 1

Related Questions