Home > Software engineering >  Converting list of lists to dataframe with incorrect format
Converting list of lists to dataframe with incorrect format

Time:10-14

I am working on a web app that will allow the user to create a dataframe from within the web app within certain parameters. This is being made with flask, and requires passing a dataframe between different pages, and converting it from a dataframe to a HTML table as necessary, and vice versa.

When I retrieve the values of the table from the client, this is how it appears:

data = request.values.lists()
[('Time', ['00:30', '03:30']), ('Blood Lactate', ['1', '1.1']), ('Velocity (km/h)', ['9', '10'])]

Note: the user cannot add columns, they can only add/remove rows.

When I try to convert this to a dataframe, this is what I get:

df = pd.Dataframe(data)
                 0               1
0             Time   [00:30, 03:30]
1    Blood Lactate         [1, 1.1]
2  Velocity (km/h)          [9, 10]

I would like if my dataframe was in this format:

      Time   Blood Lactate    Velocity (km/h)
0    00:30               1                  9
1    03:30             1.1                 10

Is there a way in pandas to convert the data into this format?

CodePudding user response:

You can convert your data to a dictionary first:

pd.DataFrame({e[0]: e[1] for  e in request.values.lists()})

Result:

        Time    Blood   Lactate   Velocity (km/h)
 0      00:30           1         9
 1      03:30           1.1       10

Edit: There is a shorter more readable way:

pd.DataFrame(dict(request.values.lists()))
  • Related