【发布时间】:2018-09-08 03:55:40
【问题描述】:
我有一个多索引 df s:
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
pd.MultiIndex(levels=[['bar', 'baz', 'foo', 'qux'], ['one', 'two']],
labels=[[0, 0, 1, 1, 2, 2, 3, 3], [0, 1, 0, 1, 0, 1, 0, 1]],
names=['first', 'second'])
s = pd.Series(np.random.randn(8), index=index)
s
我想通过匹配索引列“first”和“second”来添加一个新的索引列“zero”,其中 x,y,z 到 s。换句话说,我想重复 s 三次,但是这个附加的索引列带有 x,y,z。我尝试了重新索引(见下文),但为什么它给了我所有的 NaN?
mux=pd.MultiIndex.from_product([["x","y","z"],
s.index.get_level_values(0),
s.index.get_level_values(1)],
names=["zero","first", "second"])
t=s.reindex(mux)
t
我也尝试将匹配级别指定为“第一”和“第二”,但看起来级别只需要一个整数?
【问题讨论】:
标签: python pandas multi-index reindex