当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python Pandas DataFrame rmul方法用法及代码示例


Pandas DataFrame.rmul(~) 方法将标量、序列、Series 或 DataFrame 与源 DataFrame 中的值相乘,即:

other * DataFrame

请注意,这与 DataFrame.mul(~) 相反,它执行以下操作:

DataFrame * other
注意

除非您使用参数 axislevelfill_value ,否则 rmul(~) 相当于使用 * 运算符执行乘法。

参数

1.other | scalarsequenceSeriesDataFrame

生成的 DataFrame 将是 other 与源 DataFrame 相乘。

2. axis | intstring | optional

是否为源DataFrame的每一列或每一行广播other

说明

"index"0

每列广播other

"columns"1

每行广播 other

仅当源 DataFrame 的形状与 other 的形状不对齐时,这才相关。默认情况下,axis=1

3. level | intstring | optional

要考虑的级别的名称或整数索引。仅当您的 DataFrame 是多索引时,这才有意义。

4. fill_value | floatNone | optional

在计算之前替换NaN的值。如果两个条目都是 NaN ,则结果产品将始终是 NaN 。默认情况下,fill_value=None

返回值

由源 DataFrame 和 other 的乘积产生的新 DataFrame 。

例子

基本用法

考虑以下数据帧:

df = pd.DataFrame({"A":[2,3], "B":[4,5]})
df_other = pd.DataFrame({"A":[6,7], "B":[8,9]})



   A  B   |     A  B
0  2  4   |  0  6  8
1  3  5   |  1  7  9

计算他们的产品产量:

df.rmul(df_other)



   A   B
0  12  32
1  21  45

请注意,这相当于以下内容:

df_other * df



   A   B
0  12  32
1  21  45

广播

考虑以下 DataFrame :

df = pd.DataFrame({"A":[2,3], "B":[4,5]})
df



   A  B
0  2  4
1  3  5
行乘法

默认情况下, axis=1 ,这意味着 other 将为 df 中的每一行广播:

df.rmul([10,100])   # axis=1



   A   B
0  20  400
1  30  500

在这里,我们进行以下逐元素乘法:

10*2 100*4
10*3 100*5
逐列乘法

要为 df 中的每一列广播 other,请像这样设置 axis=0

df.mul([10,100], axis=0)



   A    B
0  20   40
1  300  500

在这里,我们进行以下逐元素乘法:

10*2 10*4
100*3 100*5

指定fill_value

考虑以下带有缺失值的DataFrames:

df = pd.DataFrame({"A":[2,np.NaN], "B":[np.NaN,5]})
df_other = pd.DataFrame({"A":[10,20],"B":[np.NaN,np.NaN]})



   A    B     |     A   B
0  2.0  NaN   |  0  10  NaN
1  NaN  5.0   |  1  20  NaN

默认情况下,当我们使用 rmul(~) 计算乘积时,任何使用 NaN 的操作都会产生 NaN

df.rmul(df_other)



   A     B
0  20.0  NaN
1  NaN   NaN

我们可以在使用 fill_value 参数执行乘法之前填充 NaN 值:

df.rmul(df_other, fill_value=100)



   A       B
0  20.0    NaN
1  2000.0  500.0

请注意,无论 fill_value 为何,两个 NaN 的乘积是 NaN

相关用法


注:本文由纯净天空筛选整理自Isshin Inada大神的英文原创作品 Pandas DataFrame | rmul method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。