保留浮动值的%格式 [英] Keep % format of float values

查看:86
本文介绍了保留浮动值的%格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将float保持为%格式?

df['growth_rate'] = df['growth_rate'].replace('%', '', regex=True).astype(float, errors='ignore')/100

将列从str更改为floats后,如何将格式从0.2345更改为23.45%?例如,将列类型转换为float后,将如下所示:

After changing the column from str to floats, how do you change the format from 0.2345 to 23.45%? For example, after the column type was converted to float, it would be like this:

    growth_rate    growth_rate2    growth_rate3
0        0.2345          0.4253          0.3643
1        0.1473             NaN          0.1735
2           NaN          0.6936          0.5925
3        0.2500          0.2746             NaN

在保持类型为float的同时,如何使它看起来像这样:

How do you make it look like this while still keeping the type in float:

    growth_rate    growth_rate2    growth_rate3
0        23.45%          42.53%          36.43%
1        14.73%             NaN          17.35%
2           NaN          69.36%          59.25%
3        25.00%          27.46%             NaN
# NaN is fine, as long as it can be performed in some calculation later on

更新:如果可能的话,我只是在寻找简单的单行代码.感谢您的输入.

Update: I'm just looking for a simple one-line code if possible. Thanks for your input.

推荐答案

您可以将列发送并通过to_string发送:

You can take your column and send it through to_string:

output = df.to_string(formatters={'growth_rate': '{:,.2%}'.format})
print(output)

 growth_rate
0      23.45%
1      14.73%
2        nan%
3      25.00%

这不会更改您的数据框(仍在float中):

This doesn't change your data frame (which is still in float):

In [ 7]: df
Out[ 7]: 
   growth_rate
0       0.2345
1       0.1473
2          NaN
3       0.2500

但会生成可打印的growth_rate列的字符串表示形式.

but generates a string representation of the growth_rate column you can print.

要输出所有列,请传递一列格式化程序,只要列数就可以:

To output all the columns, pass a list of formatters as long as the number of columns:

df['growth_rate2'] = [0.1,0.04,0.876,np.nan]
output = df.to_string(formatters=['{:,.2%}'.format]*2)

要仅以特殊格式输出特定列,请使用以列名称为键的字典:

To output only particular columns in your special format, use a dictionary with the column names as the keys:

df['growth_rate3'] = [0.071,0.02,0.,0.66]
df.to_string(formatters={'growth_rate': '{:,.2%}'.format,
                         'growth_rate3': '{:,.2%}'.format})

这篇关于保留浮动值的%格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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