How do I avoid my piece of python code from aggressively rounding off values to 1 decimal place

Related searches

I am trying to create a new column in my pandas dataframe that is the result of a basic mathematical equation performed on other columns in the dataset. The problem now is that the values captured in the column are extremely rounded up and does not represent the true values.

2.5364 should not be rounded off to 2.5 and 3.775 should not be rounded off to 3.8

I have tried to declare the denominators as floats in a bid to trick the system to supply values that look like that. ie 12/3.00 should be 4.00 but this is still returning 4.0 instead.

This is currently what I am doing:

normal_load = 3
df['FirstPart_GPA'] = ((df[first_part].sum(axis = 1, skipna = True))/(normal_load*5.00))

I set skipna to true because sometimes a column might not have any value but I still want to be able to calculate the GPA without the system throwing out any errors since any number plus NAN would give NAN.

I am working with a dataframe that looks like this:

dict = {'course1': [15,12],
        'course2': [9,6],
        'course3': [12,15],
        'course4': [15,3],
        'course5': [15,9],
        'course6': [9,12]}

df = pd.DataFrame(dict)

Note that the dataframe I have contains some null values because some courses are electives. Please help me out. I am out of ideas.

You have not defined the first_part variable in your code, so I am going to assume it is some subset of dataframe columns, e.g:

first_part=['course1', 'course2', 'course3']

All of the numbers in your dataframe are integer multiples of 3, therefore when you sum up any of them and divide by 15, you will always get a decimal number with no more than 1 digit after the decimal dot. Your values are not rounded up, they are exact.

To display numbers with two digits after the decimal dot, add a line:

pd.options.display.float_format = '{:,.2f}'.format

Now

df['FirstPart_GPA'] = ((df[first_part].sum(axis = 1, skipna = True))/(normal_load*5.00))
df
course1 course2 course3 course4 course5 course6 FirstPart_GPA
0   15  9   12  15  15  9   2.40
1   12  6   15  3   9   12  2.20

How to Round Numbers in Python – Real Python, This fluctuation may not necessarily be a nice value with only two decimal places. For example, the overall value may increase by $0.031286 one second and� The decimal module provides support for decimal floating point arithmetic. It offers several advantages over the float datatype:. Decimal “is based on a floating-point model which was designed with people in mind, and necessarily has a paramount guiding principle – computers must provide an arithmetic that works in the same way as the arithmetic that people learn at school.” – excerpt

You can add float formatting something like this:

result= "%0.2f" % your_calc_result

Example using this code:

dict = {'course1': [15,12],
        'course2': [9,6],
        'course3': [12,15],
        'course4': [15,3],
        'course5': [15,9],
        'course6': [9,12]}
df = pd.DataFrame(dict)
normal_load = 3.0
result=[]
for i in range(len(df.index)):
    result.append("%0.2f" % (float(df.loc[i].sum())/(normal_load*5.00)))
df['FirstPart_GPA']=result

Output:

   course1  course2  course3  course4  course5  course6 FirstPart_GPA
0       15        9       12       15       15        9          5.00
1       12        6       15        3        9       12          3.80

How to Round Numbers in Python, Apply Python's round() method to return a floating point number rounded off to the given ndigits digits after the decimal point. Learn about the� Python recently underwent a major version change from 2 to 3. For consistency with other courses in the department, we will be using Python 3. Python 2 is still widely used, and although Python 3 is not fully backwards compatible the two versions are very similar – so should you ever encounter Python 2 code you should find it quite familiar.

OMG! I now see what the problem is. I just threw my file into excel and did the calculation and it turns out that the code is fine. I am sorry I took any of your time and at the same time I appreciate your quick response.

I always assumed that GPAs would have lots of decimals but the code uses a 5-point grading system which means that if a student has an A in a course that has a course load of 3, she would have scored 15 points.

A student has to take 5 courses per semester. All 5 courses have a load of 3. This means that all 5 courses = 15.

So because the possible values a student can have are mostly multiples of 3 (0,3,6,9,12,15), when we divide the sum of all his units across all 5 courses by 15, 3 would always go through it ie 3+12+12+3+9/15 = 13/5

5 is so unproblematic and it would mostly not spill over in extra decimals unlike 10/3 that keeps giving me recursive 3s in the decimal part, 5 is co-operative. Therefore 13/5 = 2.6

How to round decimal places up and down in Python? � Kodify, Python can round values to a number of decimal places in different ways. This tutorial Let's look at each approach and the Python code they require. Here we use values 5 through 1 for that. The last bit of code outputs the results with the print() function. Check out my TradingView programming help. In this step-by-step tutorial, you'll learn about the print() function in Python and discover some of its lesser-known features. Avoid common mistakes, take your "hello world" to the next level, and know when to use a better alternative.

How to truncate Python numbers to integers? � Kodify, Our Python program implements that behaviour with the math.trunc() or Truncate Python values: remove decimal places This just shows that truncation is different from rounding values up To use int() , we call the function with one argument: the value we See my TradingView programming services. Python Reference Python Overview Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods Python File Methods Python Keywords Python Exceptions Python Glossary Module Reference Random Module Requests Module Math Module cMath Module Python How To

4 Methods to Round Values in Pandas DataFrame, (1) Round to specific decimal places – Single DataFrame column df['DataFrame Here is the complete Python code to round the values up using numpy: Python allows you to use a lowercase L with long, but it is recommended that you use only an uppercase L to avoid confusion with the number 1. Python displays long integers with an uppercase L.

Access Items. You cannot access items in a set by referring to an index, since sets are unordered the items has no index. But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.

Comments
  • "ie 12/3.00 should be 4.00 but this is still returning 4.0 instead." - See stackoverflow.com/questions/588004/… - 4.00 and 4.0 mean exactly the same. You can force to display the numbers with two decimal places, but that applies to ever number in that column.
  • What is first_part?
  • Cannot reproduce. The example data that you show are all multiple of 3 so all the results need only one decimal digit. And when I tweeked an number to have a sum which is not a multiple of 3, my system displayed it with 6 decimal positions.
  • Have you tried using the round() function? df['FirstPart_GPA'] = ((df.sum(axis = 1, skipna = True))/(normal_load*5.00)).round(2) Otherwise can you colloborate on the expected output?
  • Thank you @seed, the issue here is that for the original dataset that I have, the code I applied is rounding off aggressively and for a student's GPA, accuracy matters a whole lot.
  • Then could you please include a reproducible sample in your question.
  • Thank you mf Al Fafa for your input but I need the result to be saved as a new column in the dataframe. For example, the output from your code should be in the column called "FirstPart_GPA"
  • now, it will add a 'FirstPart_GPA' column to DataFrame and display the result of calculation
  • I get it now. I would try this because it looks more wholesome than my previous code and I bet I would need to implement something like this in the future. Thank you so much for your time.