我有一个具有以下结构的字典列表。
{
'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)
这种方法看起来非常hacky,我想知道是否有更加“pythonic”的方法来实现这个,或者至少是否有任何明显的优化空间。