用嵌套字典创建一个多索引的“系列" [英] Creating a multiindexed `Series` with a nested dictionary
本文介绍了用嵌套字典创建一个多索引的“系列"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我看来,我要做的事情应该简单明了,就像将其传递给构造函数一样简单,但实际上并非如此.我有如下字典.
In my mind, what I'm trying to do ought to be straightforward, as straightforward as passing it into the constructor, but in reality it's not. I have a dictionary like below.
d = {"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)}}
我想做类似pandas.Series(d)
的事情,并得到一个类似下面的Series
实例.
I would like to do something like pandas.Series(d)
and get a Series
instance like below.
russell score 0.87391482
ping 23
cantor score 0.77821932
ping 16
godel score 0.53372128
ping 35
但是我实际上得到的是下面的东西.
But what I actually get is below.
cantor {'ping': 44, 'score': 0.007408727109865398}
godel {'ping': 41, 'score': 0.9338940910283948}
russell {'ping': 74, 'score': 0.733817307366666}
有没有办法实现我想要达到的目标?
Is there a way to achieve something like what I'm trying to achieve?
推荐答案
我认为您需要 DataFrame
构造函数,带有
I think you need DataFrame
constructor with unstack
:
import pandas as pd
import numpy as np
d = {"russell": {"score": np.random.rand(), "ping": np.random.randint(10, 100)},
"cantor": {"score": np.random.rand(), "ping": np.random.randint(10, 100)},
"godel": {"score": np.random.rand(), "ping": np.random.randint(10, 100)}}
print (pd.DataFrame(d).unstack())
cantor ping 33.000000
score 0.240253
godel ping 64.000000
score 0.435040
russell ping 41.000000
score 0.171810
dtype: float64
如果需要MultiIndex
中的交换级别,请使用 stack
:
Also if need swap levels in MultiIndex
use stack
:
print (pd.DataFrame(d).stack())
ping cantor 64.000000
godel 40.000000
russell 66.000000
score cantor 0.265771
godel 0.283725
russell 0.085856
dtype: float64
这篇关于用嵌套字典创建一个多索引的“系列"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文