[Python] Why does it show SettingWithCopyWarning?

Discussão em 'Python' iniciado por Stack, Agosto 3, 2025.

  1. Stack

    Stack Membro Participativo

    I Googled how to add a row to a dataframe and found the following sample code:

    # Create a sample DataFrame
    data = {'col1': [1, 2], 'col2': ['A', 'B']}
    df1 = pd.DataFrame(data, index=['idx1', 'idx2'])
    print("Original DataFrame:")
    print(df1)


    # Define the new row data
    new_row_data = [3, 'C']
    # Define the new index label
    new_index_label = 'idx3'

    # Append the new row with the specified index
    df1.loc[new_index_label] = new_row_data

    print("\nDataFrame after appending a new row:")
    print(df1)


    It works well without giving any message. Then I used the same method to add one row in my own code:

    df_test = df.iloc[:60:3] # a datafrme for test
    row_add = df.iloc[100] # one row to add
    df_test.loc[row_add.name] = row_add.tolist()


    Here df is a dataframe of stock price (open, high, low, close, volume) with datetime object as index. df_test is like the following before manipulation:

    [​IMG]

    After the manipulation, df_test is:

    [​IMG]

    The result matches my expectation. But it gives the following message:

    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
    df_test.loc[row_add.name] = row_add.tolist()


    I want to know why it gives this message in my code, whereas no message is shown in the sample code?

    Some information can be found about SettingWithCopyWarning, e.g. SettingWithCopyWarning from Google and SettingWithCopyWarning from stackoverflow, but they are not quite relevant to my case. It's shown that it can be suppressed by

    import pandas as pd
    pd.options.mode.chained_assignment = None # default='warn'


    But I don't know whether there is any side effect.

    Continue reading...

Compartilhe esta Página