[英]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.