Lecture 1.11 Pandas

Author: Umair_learning_Python

I was able to rename POP to population. But when I try to revert to single units (from thousands), I get the following error.
Please advice. Thanks.
Umair

In [66]: df['population'] = df['population'] * 1e3
-----------error message-------------
C:\Anaconda3\lib\site-packages\ipykernel\__main__.py:1: 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

See the caveats in the documentation:

http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

  if __name__ == '__main__':
----------end of error message---------

Hi Umair,

Can you post the lines leading up to the line you have posted.

The issue is that along the way df represents a “view” of some original data (like a slice or limited range etc.). Pandas complains when trying to set values when working with an object that is a “view” of the underlying data as it will mutate the original data that it is “viewing”. One way to resolve this is that you can use a copy of the df dataframe to generate a new object of the elements the you are viewing using .copy() method.

Check out the associated link to the Pandas documentation attached to the warning

Author: Umair_learning_Python

The preceding lines were just the ones posted in the lecture. But I get your point about copy(). Thanks.
Umair

SettingWithCopyWarning is typically occurs when you try to modify a DataFrame or Series that is a result of slicing another DataFrame without explicitly making a copy. This warning is raised because changes made to the sliced data may not propagate back to the original DataFrame, leading to unexpected behavior. To fix this warning, you should ensure that you are working on a copy of the data rather than a view of it. You can use the .copy() method to create a separate copy of the DataFrame or use the .loc accessor to modify the original DataFrame directly, avoiding the creation of a potentially problematic view. By doing so, you can avoid the SettingWithCopyWarning and ensure that your changes are applied to the intended data.