https://mkaz.blog/code/python-string-format-cookbook/
1. 问题背景
在展示数据时,有时候,数字的格式杂乱无章,不利于我们直观地迅速获取数据中的信息,因此我们需要格式化数据。一般我们用于格式化pandas中的数据。
2. pandas格式化数据
df['c1'].map('{:,.2f}'.format,na_action='ignore')
- df是dataframe
- {}里面的是格式
- na_action控制是否格式化NaN
3. 格式化字符串
用于控制格式也是一个字符串,用{}包起来。以下举例示范
不加任何处理:
print("{:}".format(1234567.123456))
1234567.123456
逗号分隔:
print("{:,}".format(1234567.123456))
1,234,567.123456
保留小数点后两位:
print("{:,.2f}".format(1234567.123456))
1,234,567.12
取整:
print("{:.0f}".format(1234567.123456))
1234567
小数点后两位百分比:
print("{:.2%}".format(1234567.123456))
123456712.35%
加百分号:
print("{:.2f}%".format(1234567.123456))
1234567.12%
前后加描述:
print("this is {:,.2f} which has two decimals".format(1234567.123456))
this is 1,234,567.12 which has two decimals