0

I am trying to add a new column to a df in pandas however when I use wither of the below 2 method but somehow both results in the same warning message after execution. Is there a way to avoid these without making a copy of the df

Original df:

match_all = match[['country_id','league_id','season','stage','date','home_team_api_id','away_team_api_id','home_team_goal'
                     ,'away_team_goal']]

Method 1:

def goal_diff(matches):
    return matches['home_team_goal'] - matches['away_team_goal']
match_all['home_away_goal_diff'] = goal_diff(match_all)

Warning message

C:\Users\5150224\AppData\Local\Continuum\anaconda3\lib\site-packages\ipykernel_launcher.py:3: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy This is separate from the ipykernel package so we can avoid doing imports until

Method 2 :

match_all['home_away_goal_diff'] = match_all['home_team_goal'] - match_all['away_team_goal']

warning message:

C:\Users\5150224\AppData\Local\Continuum\anaconda3\lib\site-packages\ipykernel_launcher.py:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy """Entry point for launching an IPython kernel

Gaurav Chordiya
  • 39
  • 1
  • 12
  • Possible duplicate of [Hide all warnings in ipython](https://stackoverflow.com/questions/9031783/hide-all-warnings-in-ipython) – G. Anderson Nov 28 '18 at 21:38
  • 1
    I do not want to hide the warnings, I am looking for a more standard way to have cleaner code. The link is more on how to hide the warning messages not geeing rid of it – Gaurav Chordiya Nov 28 '18 at 21:45
  • 2
    I think `match_all` is a slice of `match` and not a copy. Can you try creating it with `match_all = match[['country_id','league_id','season','stage','date','home_team_api_id','away_team_api_id','home_team_goal' ,'away_team_goal']].copy()` and see if the warning persists? – willk Nov 28 '18 at 22:19
  • Thank you @caseWestern this did fix the issue and the warnings are gone now. – Gaurav Chordiya Nov 28 '18 at 23:04
  • Great! [This article](https://www.dataquest.io/blog/settingwithcopywarning/) does a thorough job of explaining the warning. Basically, this isn't a warning you should ignore if you want your code to run as intended. – willk Nov 29 '18 at 00:48

0 Answers0