The row values are not changed in the following iteration:
>>> df
species population
panda bear 1864
polar bear 22000
koala marsupial 80000
>>> for i, r in df.iterrows():
... r['population']=r['population']*2
...
>>> df
species population
panda bear 1864
polar bear 22000
koala marsupial 80000
Can anyone please show me how can I persist the changed values in the above iteration?
CodePudding user response:
That's because iterrows
returns copies that are disconnected from your original (df
).
Jeff Reback: You should NEVER modify something you are iterating over.
Use pandas.Series.mul
instead :
df["population"] = df["population"].mul(2)
Output :
print(df)
species population
panda bear 3728
polar bear 44000
koala marsupial 160000