PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 9, 2022

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

 August 09, 2022     decimal, pandas, python     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing