[Python] ChainedAssignmentError - Pandas 3 - Warning

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

  1. Stack

    Stack Membro Participativo

    I have project with multiple files. Many files I was using pandas by importing it. Recently I have upgraded my packages where pandas also upgraded which resulting me into 'ChainedAssignmentError'. I have went through few posts.

    Based on that I have used loc to make sure that i am writing on original instead of taking copy. Still I am getting same error. Kindly help me on this issue. Here is the snippet of my code.

    Python version is 3.13 and pandas version is 2.3.0

    import pandas as pd
    # Sample data
    data = {
    "tradingsymbol": ["NIFTY25JUN25800CE", "NIFTY2570326000CE", "NIFTY2570325800CE", "NIFTY25JUN26000CE", "NIFTY25JUN27000CE"]
    }

    # Create DataFrame
    closedPositions_df = pd.DataFrame(data)


    def strip_last_5_if_gt_5(s):
    s = str(s) # Ensure s is a string
    if len(s) > 5:
    return s[-5:] # Take the last 5 characters
    return s
    # manipulating some more on dataframe. Error raises on the line of where i apply my function.
    closedPositions_df.loc [:, 'strike'] = closedPositions_df['tradingsymbol'].str.extract(r'(\d+)(?=CE|PE)')
    closedPositions_df.loc [:, 'strike'] = closedPositions_df['strike'].astype(str).apply(strip_last_5_if_gt_5)

    # Display the DataFrame
    print(closedPositions_df)


    Error is


    FutureWarning: ChainedAssignmentError: behaviour will change in pandas 3.0! You are setting values through chained assignment. Currently this works in certain cases, but when using Copy-on-Write (which will become the default behaviour in pandas 3.0) this will never work to update the original DataFrame or Series, because the intermediate object on which we are setting values will behave as a copy. A typical example is when you are setting values in a column of a DataFrame, like:

    df["col"][row_indexer] = value

    Use df.loc[row_indexer, "col"] = values instead, to perform the assignment in a single step and ensure this keeps updating the original df.

    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
    ​

    Continue reading...

Compartilhe esta Página