Python pandas 将 4 列与小数值相乘

Python pandas multiplying 4 columns with decimal values

我有一个 pandas 数据框,其中有 4 列包含十进制值,我必须将这些十进制值相乘才能创建一个包含答案的 5 列。例如

col1   col2   col3   col4
0.03   0.02   0.01   0.05
0.12   0.32   0.05   0.03

我尝试使用以下代码进行乘法运算:

df['col5'] = df['col1']*df['col2']*df['col3']*df['col4']

我得到的值如下:

3.600000e-06
1.701000e-04

我不知道怎么读这些。我尝试将这些数字四舍五入为 8 位数字。

round(df['col5'], 8)

不起作用。然而

round(df['col5'], 6)  

有效。我想得出至少 8 个小数点。因此,我尝试使用

将该列转换为十进制列
from decimal import Decimal
df['col5'] = df['col5'].apply(Decimal)

这行得通...但它提供了很长的十进制值字符串,我无法四舍五入,因为出现错误:

TypeError: unsupported operand type(s) for *: 'decimal.Decimal' and 'float'

相反,我尝试使用 format:

将其转换为字符串
df['col5'] = format(df['col5'], ".8f")  

但出现错误:

TypeError: unsupported format string passed to Series.__format__

如何将 4 列相乘并保留第 5 列中最多 8 位小数点的值。

您可以修改 pandas 选项以显示您想要的小数位数:

df = pd.DataFrame(np.random.randn(5,5))
print(df)

pd.set_option('precision',10)
print(df)