格式化/抑制 Python Pandas 聚合结果的科学记数法

Format / Suppress Scientific Notation from Python Pandas Aggregation Results(格式化/抑制 Python Pandas 聚合结果的科学记数法)
本文介绍了格式化/抑制 Python Pandas 聚合结果的科学记数法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如何修改 pandas 中的 groupby 操作的输出格式,该操作为非常大的数字生成科学记数法?

How can one modify the format for the output from a groupby operation in pandas that produces scientific notation for very large numbers?

我知道如何在 python 中进行字符串格式化,但是在这里应用它时我不知所措.

I know how to do string formatting in python but I'm at a loss when it comes to applying it here.

df1.groupby('dept')['data1'].sum()

dept
value1       1.192433e+08
value2       1.293066e+08
value3       1.077142e+08

如果我转换为字符串,这会抑制科学记数法,但现在我只是想知道如何格式化字符串和添加小数.

This suppresses the scientific notation if I convert to string but now I'm just wondering how to string format and add decimals.

sum_sales_dept.astype(str)

推荐答案

当然,我在评论中链接的答案不是很有帮助.您可以像这样指定自己的字符串转换器.

Granted, the answer I linked in the comments is not very helpful. You can specify your own string converter like so.

In [25]: pd.set_option('display.float_format', lambda x: '%.3f' % x)

In [28]: Series(np.random.randn(3))*1000000000
Out[28]: 
0    -757322420.605
1   -1436160588.997
2   -1235116117.064
dtype: float64

我不确定这是否是首选方法,但它确实有效.

I'm not sure if that's the preferred way to do this, but it works.

纯粹出于审美目的将数字转换为字符串似乎是个坏主意,但如果你有充分的理由,这是一种方法:

Converting numbers to strings purely for aesthetic purposes seems like a bad idea, but if you have a good reason, this is one way:

In [6]: Series(np.random.randn(3)).apply(lambda x: '%.3f' % x)
Out[6]: 
0     0.026
1    -0.482
2    -0.694
dtype: object

这篇关于格式化/抑制 Python Pandas 聚合结果的科学记数法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

patching a class yields quot;AttributeError: Mock object has no attributequot; when accessing instance attributes(修补类会产生“AttributeError:Mock object has no attribute;访问实例属性时)
How to mock lt;ModelClassgt;.query.filter_by() in Flask-SqlAlchemy(如何在 Flask-SqlAlchemy 中模拟 lt;ModelClassgt;.query.filter_by())
FTPLIB error socket.gaierror: [Errno 8] nodename nor servname provided, or not known(FTPLIB 错误 socket.gaierror: [Errno 8] nodename nor servname provided, or not known)
Weird numpy.sum behavior when adding zeros(添加零时奇怪的 numpy.sum 行为)
Why does the #39;int#39; object is not callable error occur when using the sum() function?(为什么在使用 sum() 函数时会出现 int object is not callable 错误?)
How to sum in pandas by unique index in several columns?(如何通过几列中的唯一索引对 pandas 求和?)