Pandas DataFrame 浮点格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29108341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:03:53  来源:igfitidea点击:

Pandas DataFrame Float Formatting

pythonpython-2.7numpypandasformatting

提问by morningstar2651

I have a Pandas DataFrame of survey responses that I'm aggregating to averaged scores and outputting to HTML. My current code looks like this:

我有一个 Pandas DataFrame 的调查回复,我正在汇总平均分数并输出到 HTML。我当前的代码如下所示:

import pandas as pd
import numpy as np

df = pd.read_csv('survey_scores.csv', header=0)
np.round(pd.DataFrame(df.groupby('question_number').aggregate('mean').score).transpose(), 2).to_html()

It takes a DataFrame that looks kinda like this in csv...

它需要一个在 csv 中看起来有点像这样的 DataFrame ......

response_number, question_number, score
1, 1, 3.0
1, 2, 4.0
1, 3, 4.0
2, 1, 4.0
2, 2, 4.0
2, 3, 1.0

And it outputs the averaged scores to an HTML table that formats the score values like this:

它将平均分数输出到一个 HTML 表格,该表格将分数值设置为如下格式:

3.5, 4, 2.5

However, I'm trying to get the output to force each number to display two digits after the decimal point. I got it to round to two decimal points, but I'm having difficulty getting my output to format the values like this:

但是,我试图让输出强制每个数字在小数点后显示两位数。我把它四舍五入到两个小数点,但我很难让我的输出格式化这样的值:

3.50, 4.00, 2.50

How can I get these values formatted to two decimal places?

如何将这些值格式化为两位小数?

回答by morningstar2651

I've solved the problem. pandas.DataFrame.to_html()can format floats.

我已经解决了这个问题。pandas.DataFrame.to_html()可以格式化浮点数。

import pandas as pd
import numpy as np

df = pd.read_csv('survey_scores.csv', header=0)
np.round(pd.DataFrame(df.groupby('question_number').aggregate('mean').score).transpose(), 2).to_html(float_format=lambda x: '%.2f' % x)

回答by Alexander

df.groupby('question_number').aggregate('mean').score.transpose()\
.apply(lambda x: '{0:.2f}'.format(x))

Out[422]: 
question_number
1                  3.50
2                  4.00
3                  2.50
Name: score, dtype: object

回答by Bubai

Assuming you have floatvalues, format them to 2 digits.

假设您有float值,请将它们格式化为 2 位数字。

>>> print("%.2f" % 2.5)
2.50