来自list / dict / list

时间:2017-08-25 01:20:37

标签: python pandas

我有这种形式的一些数据:

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

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

3 个答案:

答案 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

答案 1 :(得分:4)

您可以使用列表推导来连接一系列数据框,每个数据框对应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

答案 2 :(得分:0)

或者您可以尝试使用pd.wide_to_long,我确实想使用lreshape,但它没有记录,个人不推荐...... T _ T

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