[Python] Why my codes trigger the SettingWithCopyWarning in pandas

Discussão em 'Python' iniciado por Stack, Junho 14, 2025.

  1. Stack

    Stack Membro Participativo

    I'm confused by this pandas warning. I'm already using the recommended .loc[,] format, but the warning persists. Can someone explain why this warning is appearing?

    df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
    sub_df = df.loc[df.A > 1]
    sub_df.loc[:, 'C'] = sub_df.A + sub_df.B


    Here is the warning message:

    <ipython-input-203-8af37ac9de96>:3: 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
    sub_df.loc[:, 'C'] = sub_df.A + sub_df.B

    Continue reading...

Compartilhe esta Página