Search code examples
pythonpandasmultiplication

Python pandas multiplying 4 columns with decimal values


I have a pandas dataframe with 4 columns containing decimal values which I have to multiply to create a 5 column with the answer. For example

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

I tried multiplying using the following code:

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

I am getting the values such as these:

3.600000e-06
1.701000e-04

I don't know how to read these. I tried rounding of these numbers to 8 digits.

round(df['col5'], 8)

does not work. However

round(df['col5'], 6)  

works. I want to derive a minimum of 8 decimal points. Hence, I tried converting the column to a Decimal column using,

from decimal import Decimal
df['col5'] = df['col5'].apply(Decimal)

This works...but it provides with with very long string of decimal values, which I could not round off as I am getting an error:

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

Instead I tried converting it to string with format:

df['col5'] = format(df['col5'], ".8f")  

but getting the error:

TypeError: unsupported format string passed to Series.__format__

How do i multiply the 4 columns and retain the values in the 5th column upto 8 decimal points.


Solution

  • You can modify pandas option to display the number of decimals you want :

    df = pd.DataFrame(np.random.randn(5,5))
    print(df)
    
    pd.set_option('precision',10)
    print(df)