简体   繁体   English

保留浮动值的%格式

[英]Keep % format of float values

How do you keep your float in the % format? 如何保持float为%格式?

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

After changing the column from str to floats, how do you change the format from 0.2345 to 23.45% ? 将列从str更改为floats后,如何将格式从0.2345更改为23.45% For example, after the column type was converted to float , it would be like this: 例如,在将列类型转换为float ,将是这样的:

    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

How do you make it look like this while still keeping the type in float : 在保持类型为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. 感谢您的输入。

You can take your column and send it through to_string : 您可以将您的专栏文章发送给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%

This doesn't change your data frame (which is still in float ): 这不会更改您的数据框(仍处于float ):

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

but generates a string representation of the growth_rate column you can print. 但会生成您可以打印的growth_rate列的字符串表示形式。

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

Try this one... 试试这个...

import math
import pandas as pd

def get_percentage(value: float):
    """ This function converts the floating-point integer into float
    type percentage string.
    :param value: A floating point integer.
    :return string: Percentage representation of the input value with % symbol at the end.
    """
    if math.isnan(value):
        return "NaN"
    else:
        return "{}%".format(round(value * 100,2))

# Create  a data frame
data = {'Growth_Rate1': [0.2345,0.1473,math.nan,0.2500],
            'Growth_Rate2': [0.4252,math.nan,0.6936,0.2746],
            'Growth_Rate3': [0.3643,0.1735,0.5925,math.nan],
        }
df = pd.DataFrame(data)

# Get the shape of the data frame
rows, cols = df.shape

# Display the data frame
print(df)

# Display the data frame with formatted values
print("---"*20)
print("\t".join(df.columns))
for row in range(rows):
    for col in range(cols):
        print(get_percentage(df.loc[row][col]), end="\t\t")
    print()
print("---"*20)

Output: 输出:

----------------------------------------------------------------------

       Growth_Rate1  Growth_Rate2  Growth_Rate3
0        0.2345        0.4252        0.3643
1        0.1473           NaN        0.1735
2           NaN        0.6936        0.5925
3        0.2500        0.2746           NaN
----------------------------------------------------------------------

Growth_Rate1    Growth_Rate2    Growth_Rate3
   23.45%          42.52%          36.43%       
   14.73%             NaN          17.35%       
      NaN          69.36%          59.25%       
   25.00%          27.46%             NaN       
----------------------------------------------------------------------

Please let me know whether it worked or not. 请让我知道它是否有效。

也许使用熊猫风格

df.style.format("{:.2%}")

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

相关问题 如何格式化 pandas dataframe 并保持原始浮点精度值 - How to format a pandas dataframe and keep original float precision values 如何更改浮点值的格式(达到特定精度)并保持浮动? - How to change format of float value(up to particular precision) and keep it float? 如何将值(以时间格式)转换为数字(浮点数) - How to convert values ( in time format) into numbers (float) “替换”将字符串转换为浮点型。 如何保持字符串格式? - “Replace” transforms string to float. How to keep string format? 熊猫数据框。 更改浮点格式。 保持类型“浮动” - Pandas data frame. Change float format. Keep type "float" 如何通过读取将带有 str 值的 CSV 数据格式化为浮点值? - How to format a CSV data with str values to float values by reading it? 在列表中浮动值,但忽略空格,但将其保留在列表中 - float values in a list but ignore blanks however keep them in the list Matplotlib:如何格式化 plt.xticks 的浮点值 - Matplotlib: How to format float values for plt.xticks 如何在python的数据预处理步骤中分割日期,并保持日期的格式为float? - How to split the date in data preprocessing step in python and keep the format of the date in float? 如何忽略unicode值并保持格式'\\ x ##'? - How can I ignore unicode values and and keep the format '\x##'?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM