【问题标题】:Pandas DataFrame from list/dict/list来自 list/dict/list 的 Pandas DataFrame
【发布时间】:2018-02-03 00:17:09
【问题描述】:

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

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

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

【问题讨论】:

  • 你如何推断​​berry c?不应该是b
  • @umutto 是正确的 - 我会编辑问题

标签: python pandas


【解决方案1】:

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

选项 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 是一个标量,我可以取其值。
  • 选项 3 是一种有趣的方法,尽管我不想在六个月后复习它并问 WTF 我当时有没有写信... (-;
  • 阿门。但是,嘿!这是一条线,必须要考虑一些事情。我听说一条线让事情变得更快,棉花糖尝起来像独角兽。
  • 我喜欢选项 3 :)
【解决方案3】:

或者您可以尝试使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-12
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 2018-08-11
    • 2011-04-24
    • 2019-06-04
    相关资源
    最近更新 更多