我想从以下字典中获得一个多索引数据框架:
d = {'a' : [1,2,3], 'b' : [4,5], 'c': [7,8]}
没有运气就试过了pd.DataFrame.from_dict(d, orient='index')
键应该是多个索引的索引第一级和值--第二级,期望的输出是:
a 1
2
3
b 4
5
c 7
8发布于 2019-10-10 20:14:27
您可以使用Pandas系列中的分解函数
pd.Series({'a': [1,2,3], 'b' : [4,5], 'c': [7,8]}).explode()
会回来
a 1
a 2
a 3
b 4
b 5
c 7
c 8发布于 2019-10-10 20:12:40
在itertools的帮助下
import pandas as pd
from itertools import chain, zip_longest
idx = chain.from_iterable([zip_longest(k, v, fillvalue=k) for k,v in d.items()])
pd.MultiIndex.from_tuples(idx)MultiIndex([('a', 1),
('a', 2),
('a', 3),
('b', 4),
('b', 5),
('c', 7),
('c', 8)],
)https://stackoverflow.com/questions/58330352
复制相似问题