我有类似的东西
df = pd.DataFrame(np.random.randint(2, 10, size = (5, 2)))
df.index = pd.MultiIndex.from_tuples([(1, 'A'), (2, 'A'), (4, 'B'),
(5, 'B'), (8, 'B')])
df.index.names = ['foo', 'bar']
df.columns = ['count1', 'count2']
df
这使:
count1 count2
foo bar
1 A 6 7
2 A 2 9
4 B 6 7
5 B 4 6
8 B 5 6
我还有一个总计列表 - 从其他地方获得 - 通过相同的“foo”索引:
totals = pd.DataFrame([2., 1., 1., 1., 10.])
totals.index = [1, 2, 4, 5, 8]
totals.index.names = ['foo']
totals
这使:
0
foo
1 2
2 1
4 1
5 1
8 10
我怎样才能划分所有列df (count1 and count2) 中的 foo 编号totals? (因此,我需要通过“foo”号码进行匹配)
我检查了这个问题 https://stackoverflow.com/questions/19501510/divide-entire-pandas-multiindex-dataframe-by-dataframe-variable,看起来应该可以解决问题,但我无法弄清楚。
I tried
df.div(totals, axis = 0)
并改变level选项中div,但没有成功。
一如既往,非常感谢您抽出时间