Pandas Change Value / Add Column

February 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
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.