Home > Enterprise >  A value is trying to be set on a copy of a slice from a DataFrame after append [duplicate]
A value is trying to be set on a copy of a slice from a DataFrame after append [duplicate]

Time:09-23

I have an empty pandas data frame and wanted to add new rows to it and then change its values. I found out that after appening the first row time and changing its values there's no problem, but if I append a second row it raises the A value is trying to be set on a copy of a slice from a DataFrame warning.

Any posible solution to avoid this problem?

Reproducible example:

import pandas as pd

table = pd.DataFrame({'A':[], 'B':[]})
newrow = {'A':False, 'B':False}

Cname = 'A'
Rname = 'a'

oldindex = list(table.index )
table = table.append(newrow, ignore_index = True)
table.index = oldindex   [Rname]

table[Cname][Rname] = True

Rname = 'b'

oldindex = list(table.index )
table = table.append(newrow, ignore_index = True)
table.index = oldindex   [Rname]

table[Cname][Rname] = True

CodePudding user response:

This warning comes because your dataframe 'table' is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of the dataframe.

To fix this error , you can replace the 2nd occurrence of the line 'table[Cname][Rname] = True' with

table.loc[Rname,Cname] = True
  • Related