[Python] What am I missing to create a loop that works?

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

  1. Stack

    Stack Membro Participativo

    I have multiple simple DFs with survey results (I've made up test data below that yields the same result). I'm trying to write a loop to select two of the seven columns so I don't have to write the same thing out each time.

    test1 = {
    "Strongly Agree": [4],
    "Agree": [2],
    "Neither Agree nor Disagree": [1],
    "Disagree": [2],
    "Strongly Disagree": [1],
    "Top 2 Box": [6],
    "Label": ["One"]
    }

    test2 = {
    "Strongly Agree": [6],
    "Agree": [2],
    "Neither Agree nor Disagree": [1],
    "Disagree": [0],
    "Strongly Disagree": [1],
    "Top 2 Box": [8],
    "Label": ["Two"]
    }
    df1 = pd.DataFrame(test1)
    df2 = pd.DataFrame(test2)

    df_list = [df1, df2]
    for df in df_list:
    df = df[["Top 2 Box", "Label"]]

    for df in df_list:
    print(df.head())


    (Or just df1.head() and df2.head()... they yield the same results as the attempted loop above.)

    I'm trying to update the DFs so they just have the two columns in the order dictated. Clearly I'm missing something. When I run the above, I just get the same DFs I started with.

    Continue reading...

Compartilhe esta Página