1

Hi When I use the following code I get the following error:

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   df['sic_code'][index] = comp_dict[key]

for index, row in df.iterrows():
    for key in comp_dict:
        if row['code'] == key:
            df['sic_code'][index] = comp_dict[key]

I have tried using the code below which does remove the error but it changes the output of the code so that the changes I want do not occur. To show you what I mean when I use the below code I get enter image description here which Is wrong when i use the above code (which produces the error) I get enter image description here.

for index, row in df.iterrows():
    for key in comp_dict:
        if row['code'] == key:
            df.loc[df['sic_code'][index]] = comp_dict[key]
JPWilson
  • 691
  • 4
  • 14
  • 1
    Try `df.loc[index, 'sic_code']`. You want to avoid `][` when you are setting values. – ALollz Jul 24 '20 at 19:48
  • 1
    the fourth question in the [`frequent`](https://stackoverflow.com/questions/tagged/pandas?tab=Frequent) tab for pandas is the [same](https://stackoverflow.com/questions/tagged/pandas?tab=Frequent) , my genuine advice is to read the frequent tab when starting on a particular tag – anky Jul 24 '20 at 19:48
  • @anky is right, this has been addressed before, however looping over rows is costly, try `df.row = df.row.replace(key, comp_dict[key])` within the second loop – RichieV Jul 24 '20 at 20:00
  • thanks for the help, to be fair I always google a fair bit before asking for help mostly because its obviously quicker than waiting for an answer - that said I will endever to check next time. – JPWilson Jul 24 '20 at 23:58
  • regarding df.row = df.row.replace(key, comp_dict[key]) i got the error 'DataFrame' object has no attribute 'row' – JPWilson Jul 24 '20 at 23:59

0 Answers0