保持浮点值的%格式

时间:2018-03-29 20:54:55

标签: python pandas

如何将float保留为%格式?

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

将列从str更改为浮点数后,如何将格式从0.2345更改为23.45%?例如,在列类型转换为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

如何在保持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

更新:我只是想找一个简单的单行代码。感谢您的投入。

3 个答案:

答案 0 :(得分:2)

您可以点按列并通过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中):

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

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

要输出所有列,请传递格式化程序列表,只要列数:

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

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

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

答案 1 :(得分:1)

试试这个...

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)

<强>输出:

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

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

请告诉我它是否有效。

答案 2 :(得分:1)

也许正在使用pandas style

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