首页 > 解决方案 > Converting list of lists with tuple into data frame?

问题描述

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
           

标签: pythonlistdataframedata-conversion

解决方案


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)

推荐阅读