Tim R
Tim R

Reputation: 37

Python DataFrame Issue with Warning

I am having trouble finding a solution for SettingWithCopyWarning in Jupyter Notebook. I would appreciate any insight and/or solutions. Thank you in advance.

Code:

matches2['players'] = list(zip(matches2['player_1_name'], matches2['player_2_name']))
g = matches2.groupby('players')
df_list = []

for group, df in g:
    df = df[['winner']]
    n = df.shape[0]
    player_1_h2h = np.zeros(n)
    player_2_h2h = np.zeros(n)
    
    p1 = group[0]
    p2 = group[1]

    for i in range(1,n):
        if df.iloc[i-1,0] == p1:
            player_1_h2h[i] = player_1_h2h[i-1] + 1
            player_2_h2h[i] = player_2_h2h[i-1]
        else:
            player_1_h2h[i] = player_1_h2h[i-1]
            player_2_h2h[i] = player_2_h2h[i-1] + 1
            
    df['player_1_h2h'] = player_1_h2h
    df['player_2_h2h'] = player_2_h2h
    
    df_list.append(df)

Error:

<ipython-input-214-d8e04df2295c>:32: 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: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  df['player_1_h2h'] = player_1_h2h
<ipython-input-214-d8e04df2295c>:33: 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: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  df['player_2_h2h'] = player_2_h2h

Upvotes: 0

Views: 47

Answers (2)

Angus L&#39;Herrou
Angus L&#39;Herrou

Reputation: 439

You can ignore this warning, as it's a false positive in this case, but if you want to avoid it entirely, you can change

df['player_1_h2h'] = player_1_h2h
df['player_2_h2h'] = player_2_h2h

to

df = df.assign(
    player_1_h2h=player_1_h2h,
    player_2_h2h=player_2_h2h
)

Upvotes: 1

Jacob Maldonado
Jacob Maldonado

Reputation: 31

I would recomend disabling the warning.

import pandas as pd
pd.options.mode.chained_assignment = None

For more information on this behavior see this question and search for the Garrett's answer

Upvotes: 3

Related Questions