Tuesday, August 9, 2022

[FIXED] How to add two columns of a dataframe as Decimals?

Issue

I am trying to add two columns together using the Decimal module in Python but can't seem to get the syntax right for this. I have 2 columns called month1 and month2 and do not want these to become floats at any point in the outcome as division and then rounding will later be required.

The month1 and month2 columns are already to several decimals as they are averages and I need to preserve this accuracy in the addition.

I can see guidance online for how to add numbers together using Decimal but not how to apply it to columns in a pandas dataframe. I've tried things like:

df['MonthTotal'] = Decimal.decimal(df['Month1']) + Decimal.decimal(df['Month1'])

What is the solution?


Solution

from decimal import Decimal

def convert_decimal(row):
    row["monthtotal"] = Decimal(row["month1"])+Decimal(row["month2"])
    return row

df = df.apply(convert_decimal, axis =1)


Answered By - Rishin Rahim
Answer Checked By - Mildred Charles (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.