--- tags: pandas, python, deep-copy, chained-indexing, SettingWithCopyWarning, 2022 --- # Returning a view versus a copy Ref.: [Returning a view versus a copy](https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy) Ref.2: [SettingwithCopyWarning: How to Fix This Warning in Pandas](https://www.dataquest.io/blog/settingwithcopywarning/) > SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy ## 狀況 pandas DataFrame 沒注意好就跳警告,就算用了所謂的 [df.copy(deep=True)](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.copy.html) 還是修不好? ## 簡答 (撰寫中...) * [參考程式碼 colab](https://colab.research.google.com/drive/1yT1SlGUH9C4WGeBGaMmesHN2qeHqodRr?usp=sharing) ## 如何觸發? 為何觸發? ### 觸發 ```python # 準備資料 df = pd.read_csv('/content/sample_data/california_housing_test.csv') # colab 內建 california_housing 資料集 df ``` ```python df[df.longitude < -122]['latitude'] = 100 ``` > /usr/local/lib/python3.7/dist-packages/ipykernel_launcher.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: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy """Entry point for launching an IPython kernel. ### 解法 (安全的寫法) ```python df = pd.read_csv('/content/sample_data/california_housing_test.csv') # colab 內建 california_housing 資料集 ``` ```python mask = (df.longitude < -122) df.loc[mask,'latitude'] = 500 df ``` > 參考自: https://www.dataquest.io/blog/settingwithcopywarning/