如何使输出在python中占百分比



我有以下代码和输出:

#Percentage of data with 95% or greated discount
print((df[df["itc_disc_95_itc_sku"] == True].shape[0] /df.shape[0])*100, 'Percent of ITC Sku discounts were between 95 and 120')
print((df[df["itc_disc_95_disc_per_coupon"] == True].shape[0] /df.shape[0])*100, 'Percent of Discounts per coupon were between 95 and 120')
print((df[df["itc_disc_95_disc_open_box"] == True].shape[0] /df.shape[0])*100, 'Percent of Open Box Discounts were between 95 and 120')
print((df[df["itc_disc_95_disc_employee"] == True].shape[0] /df.shape[0])*100, 'Percent of Employee discounts were between 95 and 120')
print((df[df["itc_disc_95_disc_overide"] == True].shape[0] /df.shape[0])*100, 'Percent of Overide discounts were between 95 and 120')
12.0676663204247 Percent of ITC Sku discounts were between 95 and 120
8.827338637725374 Percent of Discounts per coupon were between 95 and 120
0.0855575236983875 Percent of Open Box Discounts were between 95 and 120
0.022239723285513567 Percent of Employee discounts were between 95 and 120
0.0 Percent of Overide discounts were between 95 and 120

我需要在笔记本中显示数据,并希望将其格式化,使其以%的形式清晰地读取,并且只有两位小数。希望我想要的输出看起来像:

12.07% Percent of ITC Sku discounts were between 95 and 120
8.83% Percent of Discounts per coupon were between 95 and 120
0.09% Percent of Open Box Discounts were between 95 and 120
0.02% Percent of Employee discounts were between 95 and 120
0.0% Percent of Overide discounts were between 95 and 120

具有%的f字符串?那么你就不需要* 100了。

>>> x = 0.120676663204247
>>> f'{x:.2%} of all questions are not completely terrible'
'12.07% of all questions are not completely terrible'

我想你可以使用f-string,如果你想要两个小数,可以指定.2f:

print(f'{(df[df["itc_disc_95_itc_sku"] == True].shape[0] /df.shape[0])*100:.2f}%, Percent of ITC Sku discounts were between 95 and 120')

你试过这样的东西吗?

num1 = ...
percentage = '{0.2%}'.format(num1)
print(percentage)

2是你需要的小数位数,如果你想要,你可以更改它

最新更新