Converting list of lists with tuple into data frame?

Viewed 46

I have the following nested lists:

 lst = [[1, 1, 10], 
        [1, 2, 28.6], 
        [1, 3, 26.93], 
        [1, 4, 20],
        [2, 1, 6],
        [2, 2, 4],
        [2, 3, 6],
        [2, 4, 23],
        [3, 1, 12], 
        [3, 2, 23], 
        [3, 3, 13],
        [3, 4, 43]]

The first and second items point to x and y, respectively, and the third item is the value of that particular cell. So I need to convert this lists into a data frame in which the first items should be the columns and the second items should be the index, and finally the third items should be the value of that columns. Given the above example, my desired outcome should look like this:

mydata_frame:
              1       2     3    
           1  10      6     12
           2  28.6    4     23
           3  26.93   6     13
           4  20      23    43
           
3 Answers

Try with pandas:

import pandas as pd
df = pd.DataFrame(lst)
df = df.pivot_table(2, 1, 0)
df.columns = sorted(set(list(zip(*lst))[0]))
df.index.name = None
print(df)

Another solution - first create a dataframe with multi-level columns from the lst and then use .stack to shape it into final form:

df = (
    pd.DataFrame({(x, y): z for x, y, z in lst}, index=[0])
    .stack(level=1)
    .droplevel(0)
)
print(df)

Prints:

       1   2   3
1  10.00   6  12
2  28.60   4  23
3  26.93   6  13
4  20.00  23  43

Use pandas.DataFrame.pivot and rename_axis:

df = pd.DataFrame(lst).pivot(index=1, columns=0, values=2)
df = df.rename_axis(index=None, columns=None)
print(df)

Output:

       1     2     3
1  10.00   6.0  12.0
2  28.60   4.0  23.0
3  26.93   6.0  13.0
4  20.00  23.0  43.0
Related