我知道已經有很多關于如何將 pandas dict 轉換為資料框的帖子,但是我找不到討論我遇到的問題的帖子。我的字典如下所示:
[Out 23]:
{'atmosphere': 0
2 5
9 4
15 1
26 5
29 5
... ..
2621 4
6419 3
[6934 rows x 1 columns],
'communication': 0
13 1
15 1
26 1
2621 2
3119 5
... ..
6419 4
6532 1
[714 rows x 1 columns]
現在,我想要從這個字典中創建一個資料框,其中“氣氛”和“通信”是列,并且兩個專案的索引被合并,因此資料框如下所示:
index atmosphere commmunication
2 5
9 4
13 1
15 1 1
26 5 1
29 5
2621 4 2
3119 5
6419 3 4
6532 1
我已經嘗試過 pd.DataFrame.from_dict,但它將所有值保存在一行中。任何幫助深表感謝!
uj5u.com熱心網友回復:
使用concatwithDataFrame.droplevel洗掉第二級0:MultiIndex in columns
d = {'atmosphere':pd.DataFrame({0: {2: 5, 9: 4, 15: 1, 26: 5, 29: 5,
2621: 4, 6419: 3}}),
'communication':pd.DataFrame({0: {13: 1, 15: 1, 26: 1, 2621: 2,
3119: 5, 6419: 4, 6532: 1}})}
print (d['atmosphere'])
0
2 5
9 4
15 1
26 5
29 5
2621 4
6419 3
print (d['communication'])
0
13 1
15 1
26 1
2621 2
3119 5
6419 4
6532 1
df = pd.concat(d, axis=1).droplevel(1, axis=1)
print (df)
atmosphere communication
2 5.0 NaN
9 4.0 NaN
13 NaN 1.0
15 1.0 1.0
26 5.0 1.0
29 5.0 NaN
2621 4.0 2.0
3119 NaN 5.0
6419 3.0 4.0
6532 NaN 1.0
替代解決方案:
df = pd.concat({k: v[0] for k, v in d.items()}, axis=1)
uj5u.com熱心網友回復:
您可以pandas.concat在值和set_axis字典鍵上使用:
out = pd.concat(d.values(), axis=1).set_axis(d, axis=1)
輸出:
atmosphere communication
2 5.0 NaN
9 4.0 NaN
13 NaN 1.0
15 1.0 1.0
26 5.0 1.0
29 5.0 NaN
2621 4.0 2.0
3119 NaN 5.0
6419 3.0 4.0
6532 NaN 1.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/455755.html
上一篇:我想計算股票的每日收益
下一篇:如何連接列但有條件?
