包含pandas dataframe

时间:2017-04-26 13:27:22

标签: python pandas dictionary dataframe

我有一个字典a列表,如下所示:

a = {}
a[0]={}
a[0]['first_variable']=np.array([1,2,3,4,5])
a[0]['second_variable']=np.array([[1,2],[3,4],[5,6],[7,8],[9,10]])
a[1]={}
a[1]['first_variable']=np.array([1,2,3,4,5])
a[1]['second_variable']=np.array([[1,2],[3,4],[5,6],[7,8],[9,10]])

正如您所看到的,某些键包含一个数组,另一个包含矩阵......

鉴于这本词典,我想创建一个看起来像这样的数据框

a_dataframe = pd.DataFrame(columns=['dictionary','first_variable','second_variable_col1','second_variable_col2'])
a_dataframe['dictionary'] = np.array([1,1,1,1,1,2,2,2,2,2])
a_dataframe['first_variable']=np.array([1,2,3,4,5,1,2,3,4,5])
a_dataframe['second_variable_col1']=np.array([1,3,5,7,9,1,3,5,7,9])
a_dataframe['second_variable_col2']=np.array([2,4,6,8,10,2,4,6,8,10])

这应该以自动方式完成...即从字典键中取名字,如果是矩阵,则添加col1,col2等... 我还应该在pandas数据框中引入column(可能在第一个位置),它告诉我原始字典的索引..在这种情况下,该列被称为dictionary

你能帮帮我吗? 感谢

2 个答案:

答案 0 :(得分:1)

dfs = []
for c, d in a.items():
    #iterate the outer dict and reconstruct the records to handle array and matrix
    temp_dict = ({'{}_col{}'.format(k,i):e for k,v in d.items() 
                      for i,e in enumerate(np.asarray(v).T.reshape(-1,5))})
    #append the dict indicator
    temp_dict['dictionary'] = c+1
    #append the df to the df list         
    dfs.append(pd.DataFrame(temp_dict))
df = pd.concat(dfs,axis=0,ignore_index=True)
print(df)

   dictionary  first_variable_col0  second_variable_col0  second_variable_col1
0           1                    1                     1                     2
1           1                    2                     3                     4
2           1                    3                     5                     6
3           1                    4                     7                     8
4           1                    5                     9                    10
5           2                    1                     1                     2
6           2                    2                     3                     4
7           2                    3                     5                     6
8           2                    4                     7                     8
9           2                    5                     9                    10

答案 1 :(得分:0)

您可以迭代并附加到数据框列表,如下所示:

lodf = []
for k in a.keys():
    tmp_df = pd.concat([pd.DataFrame(x) for x in a[k].values()],1)
    tmp_df.insert(0,'dictionary',k)
    lodf.append(tmp_df)

pd.concat(lodf)

这样可行,但它无法解决列名问题。