0

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
unknown
  • 35
  • 5

1 Answers1

1

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
Nilaya
  • 148
  • 8
  • Replacing the las line with your sugestion I get the ValueError: Cannot assign bool to float/integer series. Edit: changed all of them and it works. Thanks – unknown Sep 22 '21 at 08:02