所以,这就是我的问题:
dfa = pd.DataFrame({"a": [["a", "b", "c"][int(k/10)] for k in range(30)],
"b": ["a" + repr([10, 20, 30, 40, 50, 60][int(k/5)]) for k in range(30)],
"c": np.arange(30),
"d": np.random.normal(size=30)}).set_index(["a","b","c"])
dfb = pd.DataFrame({"a": [["a", "b", "c"][int(k/2)] for k in range(6)],
"b": ["a" + repr([10, 20, 30, 40, 50, 60][k]) for k in range(6)],
"m": np.random.normal(size=6)**2}).set_index(["a","b"])
基本上,我有两个带有多层索引的数据框,我想要在("a", "b")
上连接后将dfa.d
除以dfb.m
。 我无法朴素地执行dfa.d / dfb.m
或join
,因为它会提示"merging with more than one level overlap on a multi-index is not implemented"
。
我找到的最直接(哈哈)的方法如下:
dfc = dfa.reset_index().set_index(["a", "b"]).join(dfb)
dfc["r"] = dfc.d / dfc.m
dfd = dfc.reset_index().set_index(["a", "b", "c"])[["r"]]
有什么快捷键吗?
dfa.loc[dfb.index]
返回所有空值,但应该返回除法的值。 - ZJS