0

Currently attempting to round a specific column on my DataFrame, column is float64 Dtype, but keeps returning the column with all the decimal places

#The conversion from objects to float
covid2=covid.fillna(1)
covid2.replace(',','', regex=True, inplace=True)
covid2['Population'] = covid2['Population'].astype(float, errors = 'raise')
covid2['Total Deaths'] = covid2['Total Deaths'].astype(float, errors = 'raise')


#Average column 
covid2['Average']=covid2['Population']/covid2["Total Deaths"]*1000

#Rounding attempt
decimals = 5    
covid2['Average'] = covid2['Average'].apply(lambda x: round(x, decimals))
covid2.head()

RESULT:

0      2.955203e+05
1      2.650322e+06
2      3.993382e+05
3      5.062042e+05
4      3.089394e+05
CrazyChucky
  • 3,263
  • 4
  • 11
  • 25
MoeCrumbs
  • 1
  • 1
  • 1
    Is `covid2.head()` actually returning the `'Average'` column? – Random Davis Mar 15 '23 at 15:09
  • I think this is more of a display issue than an issue with the values stored. Are you familiar with scientific notation? – CrazyChucky Mar 15 '23 at 15:11
  • Are you essentially wanting integer values? If so, rather than using round just use `lambda x: int(x)`, or change the type to integers, e.g., `covid2['Average'].astype(int)` – Matt Pitkin Mar 15 '23 at 15:13
  • Sorry, what's your expected result? This is working properly from what I can tell. Try just one number without Pandas for example: `x = 2.955203e+05; r = round(x, 5); r, r == x` -> `(295520.3, True)` – wjandrea Mar 15 '23 at 15:14
  • 1
    @Matt `int` truncates instead of rounding. You can just use `round` with no additional arguments: `round(x)`. – wjandrea Mar 15 '23 at 15:15
  • 1
    Do you want to round these numbers or do you want to set the `pandas.set_option('display.precision', 5)`? – JonSG Mar 15 '23 at 15:28
  • 1
    BTW, welcome to Stack Overflow! Check out [ask] for tips. See also [How to make good reproducible pandas examples](/q/20109391/4518341). You are using Pandas, right? – wjandrea Mar 15 '23 at 15:32
  • Maybe this is what you're actually looking for: [Round a series to N number of significant figures](/q/57590046/4518341) – wjandrea Mar 15 '23 at 15:43

1 Answers1

0

you can write just like the following code in my example 2 significant digits

covid2['Average'] = covid2['Average'].round(2)
wjandrea
  • 28,235
  • 9
  • 60
  • 81