Try   HackMD

Returning a view versus a copy

Ref.: Returning a view versus a copy
Ref.2: SettingwithCopyWarning: How to Fix This Warning in Pandas

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) 還是修不好?

簡答

(撰寫中)

如何觸發? 為何觸發?

觸發

# 準備資料
df = pd.read_csv('/content/sample_data/california_housing_test.csv') # colab 內建 california_housing 資料集
df
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.

解法 (安全的寫法)

df = pd.read_csv('/content/sample_data/california_housing_test.csv') # colab 內建 california_housing 資料集
mask = (df.longitude < -122)
df.loc[mask,'latitude'] = 500
df

參考自: https://www.dataquest.io/blog/settingwithcopywarning/