Subject: Dataframe labeling in python | [Warning]: A value is trying to be set on a copy of a slice from a DataFrame

Viewed 16

I'm trying to understand this waring pandas is showing me. Assume I have a large data frame with numeric values and want to label each with a dictionary.

df = pd.DataFrame({'Sex': [1, 2], 'Sports': [2, 1]})

mapping= {'Sex':{'1': 'male','2':'female'},
          'Scholarship':{'1': 'yes','2':'no'},
          'Sports':{'1': 'soccer','2':'basketball'}}

The way I'm labeling each column to it's respective value is the following

for col in df.columns:
    for key in mapping.keys():
        if col == key:
           df[col] = df[col].map(mapping[key])

This code is showing me the following error

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/pandasdocs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

Could anyone help me write this code so it does not show the above warning. And explain why is it showing this warning.

thanks!

0 Answers
Related