Search code examples
pythonlistpandasdataframetolist

Python Pandas | Create separate lists for each of the columns


I am not sure how to use tolist to achieve the following. I have a dataframe like this:

Param_1     Param_2     Param_3
-0.171321   0.0118587   -0.148752
1.93377     0.011752    1.9707
4.10144     0.0112963   4.06861
6.25064     0.0103071   5.83927

What I want is to create separate lists for each of the columns, the list name being the column label.

I don't want to keep doing:

Param_1 = df["Param_1"].values.tolist()

Please let me know if there's a way to do this. Thanks.


Solution

  • Adding .T

    df.values.T.tolist()
    Out[465]: 
    [[-0.171321, 1.93377, 4.10144, 6.25064],
     [0.0118587, 0.011752, 0.011296299999999999, 0.0103071],
     [-0.148752, 1.9707, 4.06861, 5.83927]]
    

    Or we can create the dict

    {x:df[x].tolist() for x in df.columns}
    Out[489]: 
    {'Param_1': [-0.171321, 1.93377, 4.10144, 6.25064],
     'Param_2': [0.0118587, 0.011752, 0.011296299999999999, 0.0103071],
     'Param_3': [-0.148752, 1.9707, 4.06861, 5.83927]}
    

    Or using locals (Not recommended but seems like what you need)

    variables = locals()
    for key in df.columns:
        variables["{0}".format(key)]= df[key].tolist()
    Param_1
    Out[501]: [-0.171321, 1.93377, 4.10144, 6.25064]