1
我试图将以下字典转换为适合查看眼睛的DataFrame格式。该数据字典是在访问api和解析XML之后创建的,所以我肯定愿意以不同的方式将数据放在一起,以简化过程。将字典转换为包含分层索引和列的Pandas DataFrame
我的格式是这样的(与其它两个市场未图示的水平放置在彼此的旁边):
Market1
B S
Depth1 Depth2 Depth3 Depth1 Depth2 Depth3
actionIndicator B B B S S S
limit 589 588 586 591 592 593
quantity 185.121 8.121 32.216 34.805 16.037 36.099
我想是(未示出应该被垂直堆叠的两个市场和音符重新格式深度-ordering):
B S
Depth3 Depth2 Depth1 Depth1 Depth2 Depth3
Market1 actionIndicator B B B S S S
limit 587 588 589 591 592 593
quantity 185.121 8.121 32.216 34.805 16.037 36.099
代码:
from pandas import DataFrame
data = {
'Market1': {'B': {'Depth1': {'actionIndicator': 'B',
'limit': '558',
'quantity': '8.286'},
'Depth2': {'actionIndicator': 'B', 'limit': '557', 'quantity': '8.355'},
'Depth3': {'actionIndicator': 'B', 'limit': '555', 'quantity': '18.474'}},
'S': {'Depth1': {'actionIndicator': 'S',
'limit': '560',
'quantity': '0.626'},
'Depth2': {'actionIndicator': 'S', 'limit': '561', 'quantity': '17.101'},
'Depth3': {'actionIndicator': 'S', 'limit': '562', 'quantity': '17.576'}}},
'Market2': {'B': {'Depth1': {'actionIndicator': 'B',
'limit': '478',
'quantity': '8.182'},
'Depth2': {'actionIndicator': 'B', 'limit': '477', 'quantity': '8.329'},
'Depth3': {'actionIndicator': 'B', 'limit': '475', 'quantity': '30.156'}},
'S': {'Depth1': {'actionIndicator': 'S',
'limit': '479',
'quantity': '37.483'},
'Depth2': {'actionIndicator': 'S', 'limit': '480', 'quantity': '84.416'},
'Depth3': {'actionIndicator': 'S', 'limit': '481', 'quantity': '37.659'}}},
'Market3': {'B': {'Depth1': {'actionIndicator': 'B',
'limit': '587',
'quantity': '8.18'},
'Depth2': {'actionIndicator': 'B', 'limit': '586', 'quantity': '8.382'},
'Depth3': {'actionIndicator': 'B', 'limit': '583', 'quantity': '39.548'}},
'S': {'Depth1': {'actionIndicator': 'S',
'limit': '589',
'quantity': '55.181'},
'Depth2': {'actionIndicator': 'S', 'limit': '590', 'quantity': '17.289'},
'Depth3': {'actionIndicator': 'S', 'limit': '591', 'quantity': '17.689'}}},
}
df = DataFrame.from_dict(
{(k1, k2, k3): data[k1][k2][k3] for k1 in data.keys() for k2 in
data[k1].keys() for k3 in data[k1][k2].keys()}, orient="columns")
print(df)
你看着pd.melt? – Boud
Hacky but works:'df.unstack()。reorder_levels([0,3,2,1])。unstack(level = [3,2])' –
感谢Jan.任何希望重新排序的部分“深”? –