如何从包含不同长度列表的pandas系列创建数据框

时间:2017-10-10 12:05:21

标签: python pandas dataframe

我有以下结构的熊猫系列:

> 0 [{k1:a,k2:b,k3:c},{k1:d,k2:e,k3:f}]

> 1 [{k1:g,k2:h,k3:i},{k1:j,k2:k,k3:l},{k1:ł,k2:m,k3:n}]


> 2 [{k1:o,k2:p,k3:r}

> 3 [{k1:s,k2:t,k3:w},{k1:q,k2:z,k3:w},{k1:x,k2:y,k3:z},{k1:v,k2:f,k3:g}]

正如您所看到的,此系列包含elemnts作为不同长度的列表。每个列表中的元素都是字典。我想创建数据框,看起来像这样:

>      k1    k2   k3

>   0  a     b     c

>   1  d     e     f

>   2  g     h     i

>   3  j     k     l

>   4  ł     m     n

>   5  o     p     r

>   6  s     t     w

>   7  q     z     w

>   8  x     y     z

>   9  f     v     g

我试过下面的代码:

>for index_val, series_val in series.iteritems():
>>   for dict in series_val:
>>>      for key,value in dict.items():
>>>>          actions['key']=value

然而,PyCharm停止并且什么都不产生。有没有其他方法可以做到这一点?

1 个答案:

答案 0 :(得分:1)

使用concat x = pd.Series([[{'k1':'a','k2':'b','k3':'c'},{'k1':'d','k2':'e','k3':'f'}], [{'k1':'g','k2':'h','k3':'i'},{'k1':'j','k2':'k','k3':'l'},{'k1':'ł','k2':'m','k3':'n'}], [{'k1':'o','k2':'p','k3':'r'}],[{'k1':'s','k2':'t','k3':'w'},{'k1':'q','k2':'z','k3':'w'},{'k1':'x','k2':'y','k3':'z'},{'k1':'v','k2':'f','k3':'g'}]]) df = pd.concat(x.apply(pd.DataFrame,1).tolist(),ignore_index=True)

{{1}}

输出:

   k1 k2 k3
0  a  b  c
1  d  e  f
2  g  h  i
3  j  k  l
4  ł  m  n
5  o  p  r
6  s  t  w
7  q  z  w
8  x  y  z
9  v  f  g