来自list/dict/lis的Pandas数据帧

2024-09-28 05:27:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下表格中的一些数据:

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

我想创建一个如下所示的数据帧:

^{pr2}$

当我尝试这个:

pd.DataFrame.from_records(a)

我明白了:

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

我正在使用一个循环来重新构造我的原始数据,但是我认为必须有一个更直接、更简单的methid。在


Tags: 数据fromfieldappledataframe原始数据table表格
3条回答

选项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
重建

^{pr2}$

选项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

您可以使用列表理解来连接一系列数据帧,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

或者你可以尝试使用pd.wide_to_long,我确实想用lreshape,但这是没有文档记录的,个人不建议使用pd.wide_to_long

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

^{pr2}$

相关问题 更多 >

    热门问题