pandas 从具有不同长度的列表生成数据帧

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49891200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:29:06  来源:igfitidea点击:

Generate a dataframe from list with different length

pythonpandasdataframe

提问by Garvey

Here I got many list with different length, like a=[1,2,3]and b=[2,3]

在这里,我得到了许多不同长度的列表,例如a=[1,2,3]b=[2,3]

I would like to generate a pd.DataFrame from them, by padding nanat the end of list, like this:

我想通过nan在列表末尾填充来从它们生成 pd.DataFrame ,如下所示:

   a  b
1  1  2 
2  2  3
3  3  nan

Any good idea to help me do so?

有什么好主意可以帮助我这样做吗?

回答by Zero

Use

In [9]: pd.DataFrame({'a': pd.Series(a), 'b': pd.Series(b)})
Out[9]:
   a    b
0  1  2.0
1  2  3.0
2  3  NaN

Or,

或者,

In [10]: pd.DataFrame.from_dict({'a': a, 'b': b}, orient='index').T
Out[10]:
     a    b
0  1.0  2.0
1  2.0  3.0
2  3.0  NaN