从列表/字典/列表创建Pandas DataFrame

3

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

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

我想创建一个看起来像这样的数据框:
```html

我要创建一个数据框,它长这样:

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

当我尝试这样做时:
pd.DataFrame.from_records(a)

I get this:

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

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


1
你如何推断berry c?它不应该是b吗? - umutto
@umutto 是正确的 - 我会编辑问题。 - Mike Woodward
3个回答

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。鉴于“table”是一个标量,我只需取其值即可。 - Alexander
选项3是一种有趣的方法,尽管我不想在六个月后回顾它并问自己当时写了什么... (-; - Alexander
那真是太好了。但是嘿!这只有一行,这也算什么吧。我听说一行代码可以让程序运行更快,棉花糖也会像独角兽一样好吃。 - piRSquared
我喜欢选项3 :) - BENY

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

我喜欢那个!聪明! - piRSquared
这是我使用的解决方案。完美。 - Mike Woodward

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接