从嵌套的不等长度列表

时间:2017-09-26 16:34:24

标签: python list pandas nested

所以我有一个如下列表:

aa = ['aa1', 'aa2', 'aa3', 'aa4', 'aa5']
bb = ['bb1', 'bb2', 'bb3', 'bb4']
cc = ['cc1', 'cc2', 'cc3']

然后将其创建为嵌套列表:

nest = [aa, bb, cc]

我想按如下方式创建一个数据框:

aa   bb   cc
aa1  bb1  cc1
aa2  bb2  cc2
aa3  bb3  cc3
aa4  bb4  nan
aa5  nan  nan

我试过了:

pd.DataFrame(nest, columns=['aa', 'bb', cc'])

但结果是这样的,每个列表都被写成一行(而不是列)

3 个答案:

答案 0 :(得分:4)

来自zip_longest的{​​{1}}函数执行此操作:

itertools

如果你有旧版本的pandas,你可能需要在列表构造函数中包装>>> import itertools, pandas >>> pandas.DataFrame((_ for _ in itertools.zip_longest(*nest)), columns=['aa', 'bb', 'cc']) aa bb cc 0 aa1 bb1 cc1 1 aa2 bb2 cc2 2 aa3 bb3 cc3 3 aa4 bb4 None 4 aa5 None None 。在较旧的Python上,您可能需要拨打zip_longest而不是izip_longest

答案 1 :(得分:1)

选项1

pd.DataFrame(nest, ['aa', 'bb', 'cc']).T

    aa    bb    cc
0  aa1   bb1   cc1
1  aa2   bb2   cc2
2  aa3   bb3   cc3
3  aa4   bb4  None
4  aa5  None  None

选项2
Homebrew zip_longest

f = lambda x, n: x[n] if n < len(x) else None
n, m = max(map(len, nest)), len(nest)

pd.DataFrame(
    [[f(j, i) for j in nest] for i in range(n)],
    columns=['aa', 'bb', 'cc']
)

    aa    bb    cc
0  aa1   bb1   cc1
1  aa2   bb2   cc2
2  aa3   bb3   cc3
3  aa4   bb4  None
4  aa5  None  None

答案 2 :(得分:1)

或者

pd.DataFrame(data={'value':nest},index=['aa', 'bb', 'cc']).value.apply(pd.Series).T
Out[1297]: 
    aa   bb   cc
0  aa1  bb1  cc1
1  aa2  bb2  cc2
2  aa3  bb3  cc3
3  aa4  bb4  NaN
4  aa5  NaN  NaN