gpt4 book ai didi

python - 从包含数据列表的字典列表创建 Pandas 数据框

转载 作者:行者123 更新时间:2023-11-28 16:35:27 26 4
gpt4 key购买 nike

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

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

where n = m* len(list with dictionaries)(其中'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)

这看起来非常 hacky,我想知道是否有更“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. 拉伸(stretch)线导致了包含不相关列的多索引 - 这将删除它
  4. 最后在原始索引上合并得到想要的DataFrame

关于python - 从包含数据列表的字典列表创建 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27006611/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com