2

I use the following code to create a new column in a dataframe:

# data is a dataframe object
data.loc[:,'test'] = 5

it comes with the following warning:

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

I already use .loc[], why is there still a warning? Is there any particular point I'm missing in my code? Thanks!

Gajanan Kulkarni
  • 697
  • 6
  • 22
Xihao Li
  • 45
  • 4
  • 2
    In general you should be safe here, what you're doing is the correct way to go about this. But are there any lines _before_ this line that reference or modify `df`? It is likely that you used chained indexing earlier on in your code and are now modifying in-place on that copy. – Brad Solomon Oct 20 '17 at 14:59
  • 2
    See an example of what I'm talking about [here](https://stackoverflow.com/questions/23296282/what-rules-does-pandas-use-to-generate-a-view-vs-a-copy) with the example on querying – Brad Solomon Oct 20 '17 at 15:07
  • Thanks for the insight! I actually find out I had used chained indexing some lines earlier. By killing this chained indexing problem, now my code works well. – Xihao Li Oct 23 '17 at 15:35

1 Answers1

0

Why not do,

>>> import pandas as pd
>>> data = pd.DataFrame([[1, 0], [2, 4]], columns=['unit', 'test'])
>>> data
   unit  test
0     1     0
1     2     4
>>> data['test'] = 5
>>> data
   unit  test
0     1     5
1     2     5
>>> data['another_test'] = 6
>>> data
   unit  test  another_test
0     1     5             6
1     2     5             6