[Python] Append columns to a df according to the column names from the source df

Discussão em 'Python' iniciado por Stack, Março 17, 2025.

  1. Stack

    Stack Membro Participativo

    I have a df_source. It contains either three columns, namely A_1, B_1 and C_1, or six columns, namely A_1, A_2, B_1, B_2, C_1 and C_2.

    I want to select only the A_* and B_* and save them into another df, namely df_new. The resulting df_new may contain either two columns or four columns.

    I am thinking of doing something like the following:

    df_new = df_source[["A_1", "B_1"]]
    if 'A_2' in df_new.columns:
    # Also add A_2, B_2 columns in df_new, but I don't know how to add the columns to the created df_new.


    Instead of

    df_new = df_source[["A_1", "B_1"]]
    if 'A_2' in df_new.columns:
    df_new = df_source[["A_1", "B_1", "A_2", "B_2"]]

    Continue reading...

Compartilhe esta Página