Python pandas将4列与十进制值相乘

2024-04-23 09:09:46 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

^{pr2}$

我得到的值如下:

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个小数点。在


Tags: 数据字符串答案formatpandasdf错误col1