![](/img/trans.png)
[英]Convert float to string in positional format (without scientific notation and false precision)
[英]Specify float_format differently for each column (scientific notation vs decimal precision)
我有多个列,有些是我想要的科学记数法,有些是特定级别的小数精度:
Frequency n
0 0.0023 2.3
1 0.0420 4.5
2 0.5460 6.7
3 0.1230 8.9
频率可以有很小的数量级,所以我最终得到十亿个零。 'n' 列应该有一组小数位数。
我尝试在“频率”列中执行以下操作:
fntables['Frequency'].options.display.float_format = '{:.2e}'.format
这将返回预期的错误,即“'Series' 对象没有属性 'options'”,因为这些选项位于 pandas 级实例上。
import pandas as pd
import numpy as np
# sample data
np.random.seed(10)
df = pd.DataFrame(np.random.random(5)**10, columns=['A'])
# display(df)
A
0 7.453316e-02
1 1.481116e-17
2 1.043476e-02
3 5.542183e-02
4 9.477913e-04
precision
:全局设置pd.reset_option('precision')
重置设置。pd.set_option('precision', 3)
# display(df)
A
0 7.453e-02
1 1.481e-17
2 1.043e-02
3 5.542e-02
4 9.478e-04
print(df.iloc[0, 0])
[out]:
0.07453316227023182
float_format
: 全局设置pd.reset_option('float_format')
重置设置。pd.options.display.float_format = '{:.3e}'.format
# display(df)
A
0 7.453e-02
1 1.481e-17
2 1.043e-02
3 5.542e-02
4 9.478e-04
print(df.iloc[0, 0])
[out]:
0.07453316227023182
apply
或map
: str
格式df['format'] = df.A.apply(lambda x: f'{x:0.3e}')
df['format'] = df.A.apply('{:,.3e}'.format)
df['format'] = df.A.map('{:,.3e}'.format)
# display(df)
A format
0 7.453316e-02 7.453e-02
1 1.481116e-17 1.481e-17
2 1.043476e-02 1.043e-02
3 5.542183e-02 5.542e-02
4 9.477913e-04 9.478e-04
np.format_float_scientific
: str
格式df['numpy_format'] = df.A.map(lambda x: np.format_float_scientific(x, precision = 3))
# display(df)
A numpy_format
0 7.453316e-02 7.453e-02
1 1.481116e-17 1.481e-17
2 1.043476e-02 1.043e-02
3 5.542183e-02 5.542e-02
4 9.477913e-04 9.478e-04
最终使用带有 np.format_float_scientific 方法的列表理解
fntables['A_sci'] = [np.format_float_scientific(x, precision = 3) for x in fntables['A']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.