多级列和行索引和乘法

Viv*_*mar 4 python dataframe python-3.x pandas

我有以下两个pandas数据帧.对于相应的df1 Col 2和df2列,我需要将df1乘以df2.

DF1

Col 1                A                B     
Col 2           1    2   3       1    2    3 
date                        
2017-01-01      1    2   1       8    6    2
2017-01-02      2    4   2       3    2    1
2017-01-03      3    3   5       2    3    5
Run Code Online (Sandbox Code Playgroud)

DF2

date          1      2    3
2017-01-01   20%    10%   5%
2017-01-02   30%    20%   15%
2017-01-03   40%    30%   12%
Run Code Online (Sandbox Code Playgroud)

我希望将表1的第2列与表2的相应列相乘.例如,对于2017-01-01中的列A列1,值1*20%得到0.2.请参阅下面的最终要求表:

Col 1                   A                  B        
Col 2              1    2    3       1     2      3
date                            
2017-01-01      0.2   0.2   0.05    1.6   0.6   0.1
2017-01-02      0.6   0.8   0.3     0.9   0.4   0.15
2017-01-03      1.2   0.9   0.6     0.8   0.9   0.6
Run Code Online (Sandbox Code Playgroud)

我已经尝试了3个带有日期和列范围的循环,但是df1 [i] [j] .loc [date]没有正确索引.我已经被困在这一段时间了,非常感谢帮助.

piR*_*red 6

使用level参数

df1.mul(df2, level=1)

Col 1  A      B    
Col 2  1   2  1   2
0      4  10  4  40
Run Code Online (Sandbox Code Playgroud)

建立

df1 = pd.DataFrame([
    [1, 2, 1, 8]
], columns=pd.MultiIndex.from_product([[*'AB'], [1, 2]], names=['Col 1', 'Col 2']))

df2 = pd.DataFrame([[4, 5]], columns=[1, 2])
Run Code Online (Sandbox Code Playgroud)

  • 这工作并且比循环快得多!真棒! (2认同)