簡體   English   中英

從包含數據列表的字典列表創建pandas數據幀

[英]Creating pandas dataframe from list of dictionaries containing lists of data

我有一個具有這種結構的字典列表。

    {
        '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)

也就是說,'data'中的每個元組都應該有自己的行。 到目前為止我所做的是:

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”方式來做到這一點,或者至少如果這里有任何明顯的加速。

如果您的數據格式為[{},{},...] ,則可以執行以下操作...

數據的問題在於詞典的數據鍵。

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. 使用您的詞典列表創建DataFrame
  2. 通過將數據列擴展為更多行來創建新的數據框
  3. 拉伸線導致多索引與不相關的列 - 這將刪除它
  4. 最后合並原始索引並獲得所需的DataFrame

回答這個問題時,有些數據會有所幫助。 但是,從您的數據結構中,一些示例數據可能如下所示:

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構造函數,您可以非常簡單地將數據重新pd.DataFrame為新的dict,如下所示:

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'])))

然后把它傳遞給熊貓

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具有相同的結構....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM