简体   繁体   English

将带有元组的列表列表转换为数据框?

[英]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.第一项和第二项分别指向 x 和 y,第三项是该特定单元格的值。 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
           

Try with pandas :试试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:另一个解决方案 - 首先创建一个 dataframe,其中包含来自lst的多级列,然后使用.stack将其塑造成最终形式:

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 :使用pandas.DataFrame.pivotrename_axis

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

Output: 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM