我有四舍五入的问题,这似乎很常见,但我无法通过Google搜索找到答案,所以我决定在这里提问。
这是我的数据
day reg log ad trans paid
1111 20171005 172 65 39.0 14.0 3.0
1112 20171006 211 90 46.0 17.0 4.0
1113 20171007 155 70 50.0 17.0 1.0
1114 20171008 174 71 42.0 18.0 0.0
1115 20171009 209 63 43.0 21.0 2.0
这是我的所作所为,我仍然希望%
的数量
table['% log'] = (table.log / table.reg * 100).astype(str) + '%'
table['% ad'] = (table.ad / table.reg * 100).astype(str) + '%'
table['% trans'] = (table.trans / table.reg* 100).astype(str) + '%'
table['% paid'] = (table.paid / table.reg * 100).astype(str) + '%'
这是我得到的,需要最后的四舍五入
day reg log ad trans paid % log % ad % trans % paid
1111 20171005 172 65 39.0 14.0 3.0 37.7906976744% 22.6744186047% 8.13953488372% 1.74418604651%
1112 20171006 211 90 46.0 17.0 4.0 42.654028436% 21.8009478673% 8.05687203791% 1.89573459716%
1113 20171007 155 70 50.0 17.0 1.0 45.1612903226% 32.2580645161% 10.9677419355% 0.645161290323%
1114 20171008 174 71 42.0 18.0 0.0 40.8045977011% 24.1379310345% 10.3448275862% 0.0%
1115 20171009 209 63 43.0 21.0 2.0 30.1435406699% 20.5741626794% 10.04784689% 0.956937799043%
我想要的是百分比不是太长,只是两位数。
答案 0 :(得分:2)
您需要round
:
table['% log'] = (table.log / table.reg * 100).round(2).astype(str) + '%'
更好的解决方案是按子集选择所有列,并将join
输出到原始df
:
cols = ['log','ad','trans','paid']
table =(table.join(table[cols].div(table.reg, 0)
.mul(100)
.round(2)
.astype(str)
.add('%')
.add_prefix('%% ')))
print (table)
day reg log ad trans paid % log % ad % trans % paid
1111 20171005 172 65 39.0 14.0 3.0 37.79% 22.67% 8.14% 1.74%
1112 20171006 211 90 46.0 17.0 4.0 42.65% 21.8% 8.06% 1.9%
1113 20171007 155 70 50.0 17.0 1.0 45.16% 32.26% 10.97% 0.65%
1114 20171008 174 71 42.0 18.0 0.0 40.8% 24.14% 10.34% 0.0%
1115 20171009 209 63 43.0 21.0 2.0 30.14% 20.57% 10.05% 0.96%
此外,如果需要更好的输出 - 添加0
2位小数:
table =(table.join(table[cols].div(table.reg, 0)
.mul(100)
.applymap("{0:.2f}".format)
.add('%')
.add_prefix('%% ')))
print (table)
day reg log ad trans paid % log % ad % trans % paid
1111 20171005 172 65 39.0 14.0 3.0 37.79% 22.67% 8.14% 1.74%
1112 20171006 211 90 46.0 17.0 4.0 42.65% 21.80% 8.06% 1.90%
1113 20171007 155 70 50.0 17.0 1.0 45.16% 32.26% 10.97% 0.65%
1114 20171008 174 71 42.0 18.0 0.0 40.80% 24.14% 10.34% 0.00%
1115 20171009 209 63 43.0 21.0 2.0 30.14% 20.57% 10.05% 0.96%