在我看来,我试图做的事情应该是直截了当的,就像把它传递给构造函数一样简单,但事实上并非如此。我有一个如下的字典。
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
实例。
russell score 0.87391482
ping 23
cantor score 0.77821932
ping 16
godel score 0.53372128
ping 35
但实际得到的是下面的内容。
cantor {'ping': 44, 'score': 0.007408727109865398}
godel {'ping': 41, 'score': 0.9338940910283948}
russell {'ping': 74, 'score': 0.733817307366666}
有没有办法实现我想要实现的目标?
答案 0 :(得分:1)
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
:
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