对Pandas DafaFrame中的条目进行四舍五入 [英] Rounding entries in a Pandas DafaFrame

查看:135
本文介绍了对Pandas DafaFrame中的条目进行四舍五入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用:

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

产生:

           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

我想将十进制数字四舍五入为两位数并乘以100,例如.568003应该是57摆弄了一段时间却无济于事;试过了

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')

尝试了许多其他方法都无济于事,大多数人抱怨该项目不是浮动对象……我看到Pandas系列对象有一个round方法,但是DF我没有尝试使用df.apply,但它抱怨浮动问题.

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.

推荐答案

只需使用numpy.round,例如:

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

只要round适用于所有列类型,就可以在DataFrame上使用.

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

有一些数据:

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

这篇关于对Pandas DafaFrame中的条目进行四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆