2017-08-25 161 views
3

我有这种形式的一些数据:熊猫数据帧从列表/字典/列表

a = [{'table': 'a', 'field':['apple', 'pear']}, 
    {'table': 'b', 'field':['grape', 'berry']}] 

我想创建一个数据帧,看起来像这样:

field table 
0 apple  a 
1 pear  a 
2 grape  b 
3 berry  b 

当我试试这个:

pd.DataFrame.from_records(a) 

我得到这个:

  field table 
0 [apple, pear]  a 
1 [grape, berry]  b 

我正在使用一个循环来重构我的原始数据,但我认为必须有一个更直接和更简单的方法。

+1

你如何推断'浆果C'?不应该是'b'。 – umutto

+0

@umutto是正确的 - 我将编辑问题 –

回答

4

您可以使用列表理解来连接一系列dataframes,一个用于在a每个字典。

>>> pd.concat([pd.DataFrame({'table': d['table'], # Per @piRSquared for simplification. 
          'field': d['field']}) 
       for d in a]).reset_index(drop=True) 
    field table 
0 apple  a 
1 pear  a 
2 grape  b 
3 berry  b 
+0

我喜欢那样!聪明! – piRSquared

+0

这是我使用的解决方案。完善。 –

4

选项1
理解

pd.DataFrame([{'table': d['table'], 'field': f} for d in a for f in d['field']]) 

    field table 
0 apple  a 
1 pear  a 
2 grape  b 
3 berry  b 

选项2
重建

d1 = pd.DataFrame(a) 
pd.DataFrame(dict(
    table=d1.table.repeat(d1.field.str.len()), 
    field=np.concatenate(d1.field) 
)).reset_index(drop=True) 

    field table 
0 apple  a 
1 pear  a 
2 grape  b 
3 berry  b 

选项3
魔方

pd.DataFrame(a).set_index('table').field.apply(pd.Series) \ 
    .stack().reset_index('table', name='field').reset_index(drop=True) 

    table field 
0  a apple 
1  a pear 
2  b grape 
3  b berry 
+0

我更喜欢选项1.鉴于'table'是一个标量,我可以只取其值。 – Alexander

+0

选项3是一个有趣的方法,虽然我不想在六个月后检查它,并询问WTF是否写回当时...( - ; – Alexander

+0

阿门那,但嘿!这是一条线,我听说一条线可以让事情变得更快,而棉花糖就像独角兽一样。 – piRSquared

0

或者你可以尝试使用pd.wide_to_long,我想使用lreshape,却是无证和个人不推荐...牛逼_牛逼

a = [{'table': 'a', 'field':['apple', 'pear']}, 
    {'table': 'b', 'field':['grape', 'berry']}] 
df=pd.DataFrame.from_records(a) 

df[['Feild1','Feild2']]=df.field.apply(pd.Series) 
pd.wide_to_long(df,['Feild'],'table','lol').reset_index().drop('lol',axis=1).sort_values('table') 

Out[74]: 
    table Feild 
0  a apple 
2  a pear 
1  b grape 
3  b berry