2

I always get this warning when I try to create a column, what can I do differently? Thank you.

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/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  foodie['Age'] = foodie['questions_135557_how_old_are_you']

enter image description here

mlboy
  • 41
  • 6
  • 1
    This is a warning, not an error – not_speshal Aug 04 '21 at 20:11
  • 1
    The thing that is difficult to understand about this warning is it is letting you know that you are _setting_ to a copy of a slice. Meaning, that `foodie` is _already_ a copy of some dataframe when you try to create a new column. At some point __before__ these lines you must have done something like `foodie = df[some columns]`, when you should have done something like `foodie = df[some columns].copy()`. – Henry Ecker Aug 04 '21 at 21:02

2 Answers2

2

It's a warning, not an error, but one you should handle
If you're just trying to change the names of the columns, use the rename method

foodie = foodie.rename(columns={
    'questions_135557_how_old_are_you': 'Age',
    'questions_134999_where_are_you_eating_at_the_moment': 'Location'
})
ti7
  • 16,375
  • 6
  • 40
  • 68
Muhteva
  • 2,729
  • 2
  • 9
  • 21
1

It's just a warning. If you want to hide the error put this line after the import pandas as pd line...

pd.options.mode.chained_assignment = None

If you want to see them again comment it out and restart the kernel.

MDR
  • 2,610
  • 1
  • 8
  • 18
  • This is not really what they want though, they'll end up with _new_ columns (for which they would want to use `.loc[:, "Age"]`), _and_ not see the warning which has helped lead them here and alert that something is up! it appears they want to _rename_ the columns, which they can do with `.rename()` – ti7 Aug 04 '21 at 20:30