请考虑这两个数据框。
import pandas as pd
cols = ['F', 'D']
s_ind = pd.MultiIndex.from_arrays([['A', 'A', 'A'], ['B', 'B', 'B'], ['C', 'C', 'C'], ['D', 'E', 'F']],
names=('cat1', 'cat2', 'cat3', 'cat4'))
s = pd.DataFrame(data=[[1,4], [2,5], [3,6]], columns=cols, index=s_ind)
所以 s 是:
F D
cat1 cat2 cat3 cat4
A B C D 1 4
E 2 5
F 3 6
和...
ib_ind = pd.MultiIndex.from_arrays([['A'], ['B'], ['C']], names=['cat1', 'cat2', 'cat3'])
ib = pd.DataFrame(data=[[7, 8]], columns=cols, index=ib_ind)
所以 ib 是:
F D
cat1 cat2 cat3
A B C 7 8
无论我使用轴 0(显示)还是轴 1(未显示)相乘,我都会收到相同的结果。看这里:
print(ib.mul(s, axis=0))
F D
cat1 cat2 cat3 cat4
A B C D 7 32
E 14 40
F 21 48
问题:如何执行乘法以便将其作为输出接收?
print(pd.DataFrame(data=[[8*1,8*4], [0,0], [7*3,7*6]], columns=cols, index=s_ind))
F D
cat1 cat2 cat3 cat4
A B C D 8 32
E 0 0
F 21 42
注意E行为0是因为ib中没有对应的E列可以相乘。或者,nans 也可以。
最佳答案
你可以试试unstack
对于 s
和 multiply
ib
和 axis=1
上的 level=1
,然后是 stack
它回来了reindex
使用 fill_value=0
final = ib.mul(s.unstack(),level=1,axis=1).stack().reindex(s.index,fill_value=0)
# or: ib.mul(s.unstack('cat4'),level=1,axis=1).stack().reindex(s.index,fill_value=0)
@piRSquared 建议的另一种方法只涉及一次 reshape (因此更快)是 rename
乘法时要匹配的索引的索引然后 stack
和 reindex
相乘后:
s.mul(ib.rename_axis('cat4', axis=1).stack().reindex(s.index, fill_value=0), axis=0)
F D
cat1 cat2 cat3 cat4
A B C D 8.0 32.0
E 0.0 0.0
F 21.0 42.0
关于python - 将两个多索引数据帧与不同但相似的索引和列相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60044177/