熊猫:两个数据帧的元素乘法

Zhu*_*arb 16 python multiplication dataframe pandas

我知道如何在两个Pandas数据帧之间进行逐元素乘法.但是,当两个数据帧的尺寸不兼容时,事情变得更加复杂.例如下面df * df2是直截了当的,但是df * df3有一个问题:

df = pd.DataFrame({'col1' : [1.0] * 5, 
                   'col2' : [2.0] * 5, 
                   'col3' : [3.0] * 5 }, index = range(1,6),)
df2 = pd.DataFrame({'col1' : [10.0] * 5, 
                    'col2' : [100.0] * 5, 
                    'col3' : [1000.0] * 5 }, index = range(1,6),)
df3 = pd.DataFrame({'col1' : [0.1] * 5}, index = range(1,6),)

df.mul(df2, 1) # element by element multiplication no problems

df.mul(df3, 1) # df(row*col) is not equal to df3(row*col)
   col1  col2  col3
1   0.1   NaN   NaN
2   0.1   NaN   NaN
3   0.1   NaN   NaN
4   0.1   NaN   NaN
5   0.1   NaN   NaN
Run Code Online (Sandbox Code Playgroud)

在上面的情况下,我如何将每列df与df3.col1相乘

我的尝试:我试图复制df3.col1 len(df.columns.values)时间以获得与以下相同维度的数据帧df:

df3 = pd.DataFrame([df3.col1 for n in range(len(df.columns.values)) ])
df3
        1    2    3    4    5
col1  0.1  0.1  0.1  0.1  0.1
col1  0.1  0.1  0.1  0.1  0.1
col1  0.1  0.1  0.1  0.1  0.1
Run Code Online (Sandbox Code Playgroud)

但这会创建一个尺寸为3*5的数据框,而我的数据框则为5*3.我知道我可以采用转置df3.T()来获得我需要的东西,但我认为这不是最快的方式.

unu*_*tbu 30

In [161]: pd.DataFrame(df.values*df2.values, columns=df.columns, index=df.index)
Out[161]: 
   col1  col2  col3
1    10   200  3000
2    10   200  3000
3    10   200  3000
4    10   200  3000
5    10   200  3000
Run Code Online (Sandbox Code Playgroud)


The*_*Cat 12

一种更简单的方法就是将要保留其colnames的数据帧与另一个的值(即numpy数组)相乘,如下所示:

In [63]: df * df2.values
Out[63]: 
   col1  col2  col3
1    10   200  3000
2    10   200  3000
3    10   200  3000
4    10   200  3000
5    10   200  3000
Run Code Online (Sandbox Code Playgroud)

这样您就不必编写所有新的数据框样板文件.


Ami*_*ani 5

要利用 Pandas 广播属性,您可以使用multiply.

df.multiply(df3['col1'], axis=0)
Run Code Online (Sandbox Code Playgroud)