如何从多个常见元素的嵌套列表中创建数据框 [英] How to create a dataframe from a nested list of multiple common elements

查看:77
本文介绍了如何从多个常见元素的嵌套列表中创建数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有 任何 个嵌套列表

Say I have any nested list, for example

A = [[120, 'Date1', 1.03], [120, 'Date2', 1.04], [120, 'Date3', 1.02], [240, 'Date1', 1.06], [240,'Date2', 0.98],
     [240, 'Date3', 1.04], [381, 'Date2', 1.03], [381, 'Date3', 0.85]]

每个子列表的第一个元素是库存编号,第二个是日期,第三个是相应的值.我想创建一个数据框,其中列标题是库存编号,行标题是日期,元素是相应的(第三个元素)值.我不确定如何做到这一点.我想形成这样的东西:

The first element of each sub-list is the stock number, the second the date, and the third a corresponding value. I want to create a dataframe where the column headings are the stock number, row headings are the date and the elements are the corresponding (third element) values. I am not directly sure on how I would do this. I want to form something like this:

      120     240    381
Date1 1.03    1.06   NaN
Date2 1.04    0.98   1.03
Date3 1.02    1.04   0.85

但是我想为 任何 个大小的嵌套列表形成这个列表,所以我不能只为数据框键入每个变量.任何帮助将不胜感激.

But I want to form this for any size nested list, so I can't just type in each variable for the dataframe. Any help would be greatly appreciated.

谢谢.

推荐答案

通过构造函数创建DataFrame,然后

Create DataFrame by constructor and then DataFrame.pivot with DataFrame.rename_axis:

df = pd.DataFrame(A).pivot(1,0,2).rename_axis(index=None, columns=None)
print (df)
        120   240   381
Date1  1.03  1.06   NaN
Date2  1.04  0.98  1.03
Date3  1.02  1.04  0.85

这篇关于如何从多个常见元素的嵌套列表中创建数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆