[英]Pandas Dataframe from Python nested dictionary
我正在嘗試從python嵌套字典創建一個Pandas數據框,如下所示:
dictionary = {'user1' : {'a': np.array([1,2,3,4]),
'b': np.array([6,7,8,9])},
'user2' : {'a': np.array([2,3,4,5]),
'b': np.array([7,8,9,1])}}
我希望數據框看起來像這樣:
a_w a_x a_y a_z b_w b_x b_y b_z
user1 1 2 3 4 6 7 8 9
user2 2 3 4 5 7 8 9 1
編輯:(其中w,x,y,z是告訴數組中的值代表什么的標記)
我試圖在這些問題中修改解決方案: 嵌套字典到多索引數據框,其中字典鍵是列標簽
但無法獲得正確的表格。
任何幫助都會很棒,謝謝。
你可以用字典理解完成整個事情,並使用enumerate
來跟蹤每個元素的索引,給你一些相似的排序。
d = {
k: {f'{ik}_{idx}': el for ik, iv in v.items() for idx, el in enumerate(iv)}
for k, v in dictionary.items()
}
pd.DataFrame.from_dict(d, orient='index')
a_0 a_1 a_2 a_3 b_0 b_1 b_2 b_3
user1 1 2 3 4 6 7 8 9
user2 2 3 4 5 7 8 9 1
擁有重復的列名稱很少是一個好主意..但是你走了,
更新2
result = pd.concat({key:pd.DataFrame(val,index=['w','x','y','z']) for key,val in dictionary.items()})
.unstack(-1)
你知道嗎,我要在列中留下多索引而不是_連接。 以這種方式離開通常會更靈活。
更新1
result = (pd.concat({key:pd.DataFrame(val) for key,val in dictionary.items()})
.unstack(-1).droplevel(1,axis=1)
原版的
result = (pd.concat({key:pd.DataFrame(val) for key,val in dictionary.items()})
.unstack(-1).T
.reset_index(level=1,drop=True).T)
result
a a a a b b b b
user1 1 2 3 4 6 7 8 9
user2 2 3 4 5 7 8 9 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.