[Python] Convert one DataFrame row to flat list

Discussão em 'Python' iniciado por Stack, Maio 5, 2025.

  1. Stack

    Stack Membro Participativo

    I new to Python and I'm therefore having trouble converting a row in a DataFrame into a flat list. To do this I use the following code:

    Toy DataFrame:

    import pandas as pd
    d = {
    "a": [1, 2, 3, 4, 5],
    "b": [9, 8, 7, 6, 5],
    "n": ["a", "b", "c", "d", "e"]
    }

    df = pd.DataFrame(d)


    My code:

    df_note = df.loc[df.n == "d", ["a", "b"]].values #convert to array
    df_note = df_note.tolist() #convert to nested list
    df_note = reduce(lambda x, y: x + y, df_note) #convert to flat list


    To me this code appears to be both gross and inefficient. The fact that I convert to an array before a list is what is causing the problem, i.e. the list to be nested. That withstanding, I can not find a means of converting the row directly to a list. Any advice?

    This question is not a dupe of this. In my case, I want the list to be flat.

    Continue reading...

Compartilhe esta Página