Pandas Change Value / Add Column

Feb 21, 2021
SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
import pandas as pd items = [  {'name': 'Desmond', 'rank': 1},  {'name': 'Jack', 'rank': 2},  {'name': 'Elon', 'rank': 3}]df = pd.DataFrame(items) 

The following works with a warning

for index, row in df.iterrows():  df['rank'][index] = row['rank'] + 100
SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

Use this instead

for index, row in df.iterrows():  df.at[index, 'rank'] = row['rank'] + 100

Add new column

for index, row in df.iterrows():  df.at[index, 'rank2'] = row['rank'] + 100

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.