从具有不同长度的列表生成数据框
问题描述:
这里有很多长度不同的列表,例如a=[1,2,3]
和b=[2,3]
Here I got many list with different length, like a=[1,2,3]
and b=[2,3]
我想通过在列表末尾填充nan
来从它们生成pd.DataFrame,如下所示:
I would like to generate a pd.DataFrame from them, by padding nan
at the end of list, like this:
a b
1 1 2
2 2 3
3 3 nan
有什么好主意可以帮助我吗?
Any good idea to help me do so?
答
使用
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
或者,
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