首页 > 解决方案 > 列表中的 Concat 系列

问题描述

我的 中有一些series对象list,每个条目都包含:

1.月份数(一月:1,二月:2 ...)作为键

2.series对象作为值

像这样

x = [
    {1: AAA    1
        BBB    1
        CCC    1
        DDD    1
    Name: test1, dtype: int64},

    {2: AAA    3
        CCC    2
        EEE    1
    Name: test1, dtype: int64}
]

我想将这些系列加入一个数据框,看起来像这样

Index, month, AAA, BBB, CCC, DDD, EEE
1      1       1    1    1    1    NaN
2      2       3    NaN  2    NaN  1



标签: pythonpandas

解决方案


使用嵌套的dict理解来扁平化dict列表并传递给concat最后一个转置:

x = [{1:pd.Series([1,1,1], index=list('abc'))}, {2:pd.Series([2,1], index=list('bc'))}]

print (x)
[{1: a    1
b    1
c    1
dtype: int64}, {2: b    2
c    1
dtype: int64}]
                
df = pd.concat({k: v for y in x for k, v in y.items()}, axis=1).T
print (df)
     a    b    c
1  1.0  1.0  1.0
2  NaN  2.0  1.0

推荐阅读