此問題與this one有關。這一次我想更進一步。給定一個字典,如:使用嵌套字典創建多索引`DataFrame`
dd = {0: {"russell": {"score": numpy.random.rand(), "ping": numpy.random.randint(10, 100)},
"cantor": {"score": numpy.random.rand(), "ping": numpy.random.randint(10, 100)},
"godel": {"score": numpy.random.rand(), "ping": numpy.random.randint(10, 100)}},
1: {"russell": {"score": numpy.random.rand(), "ping": numpy.random.randint(10, 100)},
"cantor": {"score": numpy.random.rand(), "ping": numpy.random.randint(10, 100)},
"godel": {"score": numpy.random.rand(), "ping": numpy.random.randint(10, 100)}}}
或類似的列表:
ll = [{"russell": {"score": numpy.random.rand(), "ping": numpy.random.randint(10, 100)},
"cantor": {"score": numpy.random.rand(), "ping": numpy.random.randint(10, 100)},
"godel": {"score": numpy.random.rand(), "ping": numpy.random.randint(10, 100)}},
{"russell": {"score": numpy.random.rand(), "ping": numpy.random.randint(10, 100)},
"cantor": {"score": numpy.random.rand(), "ping": numpy.random.randint(10, 100)},
"godel": {"score": numpy.random.rand(), "ping": numpy.random.randint(10, 100)}}]
我想構造一個DataFrame
,如:
russell godel cantor
score ping score ping score ping
0 0.17473916938994682 40 0.3443303845926545 47 0.43576522521017247 42
1 0.7341005512329682 22 0.14682222267827938 81 0.5662517436162526 59
這裏我們可以看到列索引是MultiIndex
。有沒有辦法實現這一點?如果我嘗試pandas.DataFrame.from_dict(dd, orient="index")
或pandas.DataFrame(ll)
然後我得到:
russell godel cantor
0 {'score': 0.17473916938994682, 'ping': 40} {'score': 0.3443303845926545, 'ping': 47} {'score': 0.43576522521017247, 'ping': 42}
1 {'score': 0.7341005512329682, 'ping': 22} {'score': 0.14682222267827938, 'ping': 81} {'score': 0.5662517436162526, 'ping': 59}
這不是我想要的。
你親自幫助我很多熊貓。非常感謝你。 – Ray