从包含数据列表的字典列表创建pandas数据帧

时间:2014-11-19 00:08:24

标签: python pandas

我有一个具有这种结构的词典列表。

    {
        'data' : [[year1, value1], [year2, value2], ... m entries],
        'description' : string,
        'end' : string,
        'f' : string,
        'lastHistoricalperiod' : string, 
        'name' : string,
        'series_id' : string,
        'start' : int,
        'units' : string,
        'unitsshort' : string,
        'updated' : string
    }

我想把它放在一个看起来像

的pandas DataFrame中
   year       value  updated                   (other dict keys ... )
0  2040  120.592468  2014-05-23T12:06:16-0400  other key-values
1  2039  120.189987  2014-05-23T12:06:16-0400  ...
2  other year-value pairs ...
...
n

其中n = m * len(带字典的列表)(其中每个列表的长度在' data' = m)

即,数据中的每个元组都是'应该有自己的行。到目前为止我所做的是:

x = [list of dictionaries as described above]
# Create Empty Data Frame
output = pd.DataFrame()

    # Loop through each dictionary in the list
    for dictionary in x:
        # Create a new DataFrame from the 2-D list alone.
        data = dictionary['data']
        y = pd.DataFrame(data, columns = ['year', 'value'])
        # Loop through all the other dictionary key-value pairs and fill in values
        for key in dictionary:
            if key != 'data':
                y[key] = dictionary[key]
        # Concatenate most recent output with the dframe from this dictionary.
        output = pd.concat([output_frame, y], ignore_index = True)

这看起来非常h​​acky,我想知道是否有更多的pythonic'这样做的方法,或者至少在这里有任何明显的加速。

2 个答案:

答案 0 :(得分:3)

如果您的数据采用[{},{},...]格式,则可以执行以下操作...

您的数据存在问题,在字典的数据键中。

df = pd.DataFrame(data)
fix = df.groupby(level=0)['data'].apply(lambda x:pd.DataFrame(x.iloc[0],columns = ['Year','Value']))
fix = fix.reset_index(level=1,drop=True)
df = pd.merge(fix,df.drop(['data'],1),how='inner',left_index=True,right_index=True)

代码执行以下操作......

  1. 使用您的词典列表
  2. 创建一个DataFrame
  3. 通过将数据列扩展为更多行来创建新的数据框
  4. 拉伸线导致多索引与无关列 - 这将其删除
  5. 最后合并原始索引并获得所需的DataFrame

答案 1 :(得分:0)

回答这个问题时,有些数据会有所帮助。但是,从您的数据结构中,一些示例数据可能如下所示:

dict_list = [{'data'            : [['1999', 1], ['2000', 2], ['2001', 3]],
              'description'     : 'foo_dictionary',
              'end'             : 'foo1',
              'f'               : 'foo2',},
             {'data'            : [['2002', 4], ['2003', 5]],
              'description'     : 'bar_dictionary',
              'end'             : 'bar1',
              'f'               : 'bar2',}
             ]

我的建议是将这些数据操作并重新整形为新的字典,然后简单地将该字典传递给DataFrame构造函数。为了将字典传递给pd.DataFrame构造函数,您可以非常简单地将数据重新整形为新的字典,如下所示:

data_dict = {'years'        : [],
             'value'        : [],
             'description'  : [],
             'end'          : [],
             'f'            : [],}

for dictionary in dict_list:
    data_dict['years'].extend([elem[0] for elem in dictionary['data']])
    data_dict['value'].extend([elem[1] for elem in dictionary['data']])
    data_dict['description'].extend(dictionary['description'] for x in xrange(len(dictionary['data'])))
    data_dict['end'].extend(dictionary['end'] for x in xrange(len(dictionary['data'])))
    data_dict['f'].extend(dictionary['f'] for x in xrange(len(dictionary['data'])))

然后将其传递给pandas

import pandas as pd
pd.DataFrame(data_dict)

给出了以下输出:

      description   end     f  value years
0  foo_dictionary  foo1  foo2      1  1999
1  foo_dictionary  foo1  foo2      2  2000
2  foo_dictionary  foo1  foo2      3  2001
3  bar_dictionary  bar1  bar2      4  2002
4  bar_dictionary  bar1  bar2      5  2003

我想说如果这是你想要的输出类型,那么这个系统将是一个不错的简化。

事实上,您可以通过创建year:value字典以及其他val的dict来进一步简化它。然后你不必输入新的字典,你可以运行嵌套的for循环。这看起来如下:

year_val_dict = {'years'        : [],
                 'value'        : []}
other_val_dict = {_key : [] for _key in dict_list[0] if _key!='data'}

for dictionary in dict_list:
    year_val_dict['years'].extend([elem[0] for elem in dictionary['data']])
    year_val_dict['value'].extend([elem[1] for elem in dictionary['data']])
    for _key in other_val_dict:
        other_val_dict[_key].extend(dictionary[_key] for x in xrange(len(dictionary['data'])))

year_val_dict.update(other_val_dict)
pd.DataFrame(year_val_dict)

注意,这当然假设dict_list中的所有dicts都具有相同的结构....

相关问题