How to create a column that is calculated each time I change a value in the df?

I have a data frame that is like this
I would like that the column C will always be equal to “A” + “B” when I change one of these numbers in the df.

Thks for your help

import pandas as pd
import streamlit as st

df = pd.DataFrame({"A": [1, 2, 3], "B": [2, 3, 4]})

df["C"] = df["A"] + df["B"]

st.data_editor(df)

I am afraid that it is impossible. I tried for about 3 hours, then made many types of AIs attempt, and they all had to make another editor. If you figure it out, :clap:.

What about this?

import streamlit as st
import pandas as pd


# 1. Create a sample dataframe
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df['C'] = df['A'] + df['B']

# 2. Add df to session state if it doesn't exist
if 'df' not in st.session_state:
    st.session_state['df'] = df

# 3. Create an "on change" function that will be called when the data_editor is changed
#    and update the original dataframe with the new values
def on_change():
    # print(st.session_state['data_editor'])

    # Example of data_editor:
    # {'edited_rows': {0: {'A': 3}}, 'added_rows': [], 'deleted_rows': []}
    edited_rows = st.session_state['data_editor']['edited_rows']

    # now update original dataframe with the new values
    for index, row in edited_rows.items():
        for col, value in row.items():
            if col in df.columns:
                st.session_state['df'].at[index, col] = value
            else:
                st.warning(f"Column {col} does not exist in the dataframe.")

    # Recalculate column C based on the updated values in A and B
    st.session_state['df']['C'] = st.session_state['df']['A'] + st.session_state['df']['B']


st.data_editor(
    st.session_state['df'],
    disabled=['C'],  # Disable editing for column C that is calculated from A and B
    key='data_editor',
    on_change=on_change
)

# print(st.session_state['df'])

The effect is the following:
streamlit-df_test-2025-05-12-09-05-72

2 Likes