简体   繁体   English

熊猫DataFrame浮动格式

[英]Pandas DataFrame Float Formatting

I have a Pandas DataFrame of survey responses that I'm aggregating to averaged scores and outputting to HTML. 我有一个调查答复的Pandas DataFrame,我将这些答复汇总到平均分数并输出到HTML。 My current code looks like this: 我当前的代码如下所示:

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? 如何将这些值格式化为两位小数?

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

Assuming you have float values, format them to 2 digits. 假设您有float值,请将其格式化为2位数字。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM