Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding entries in a Pandas DafaFrame

Using :

newdf3.pivot_table(rows=['Quradate'],aggfunc=np.mean)

which yields:

           Alabama_exp  Credit_exp  Inventory_exp   National_exp    Price_exp   Sales_exp
Quradate                        
2010-01-15   0.568003    0.404481    0.488601    0.483097    0.431211    0.570755
2010-04-15   0.543620    0.385417    0.455078    0.468750    0.408203    0.564453

I'd like to get the decimal numbers rounded to two digit and multiplied by 100 eg .568003 should be 57 been fiddling with it for a while to no avail; tried this

newdf3.pivot_table(rows=['Quradate'],aggfunc=np.mean).apply(round(2)) #and got:
TypeError: ("'float' object is not callable", u'occurred at index Alabama_exp')

Tried a number of other approaches to no avail most complain about the item not being a float... I see that the Pandas series object has a round method but DF does not I tried using df.apply but it complained about the float issue.

like image 279
dartdog Avatar asked Sep 30 '13 17:09

dartdog


People also ask

What does round () do in pandas?

The round() method rounds the values in the DataFrame into numbers with the specified number of decimals, default 0 decimals.

How do you get 2 decimal places on pandas?

float_format to "{:,. 2f}". format to display float values to two decimal places.

Do I round DF up or down?

If a problem requires you to find critical values and the exact degrees of freedom is not listed, you always round down to the next smallest number.


1 Answers

Just use numpy.round, e.g.:

100 * np.round(newdf3.pivot_table(rows=['Quradate'], aggfunc=np.mean), 2) 

As long as round is appropriate for all column types, this works on a DataFrame.

With some data:

In [9]: dfrm
Out[9]:
          A         B         C
0 -1.312700  0.760710  1.044006
1 -0.792521 -0.076913  0.087334
2 -0.557738  0.982031  1.365357
3  1.013947  0.345896 -0.356652
4  1.278278 -0.195477  0.550492
5  0.116599 -0.670163 -1.290245
6 -1.808143 -0.818014  0.713614
7  0.233726  0.634349  0.561103
8  2.344671 -2.331232 -0.759296
9 -1.658047  1.756503 -0.996620

In [10]: 100*np.round(dfrm, 2)
Out[10]:
     A    B    C
0 -131   76  104
1  -79   -8    9
2  -56   98  137
3  101   35  -36
4  128  -20   55
5   12  -67 -129
6 -181  -82   71
7   23   63   56
8  234 -233  -76
9 -166  176 -100
like image 162
ely Avatar answered Sep 27 '22 21:09

ely