简体   繁体   English

如何格式化 pandas dataframe 并保持原始浮点精度值

[英]How to format a pandas dataframe and keep original float precision values

Im using a pandas dataframe to load a received payload, and when format it is not formatted as I would like, example of my code:我使用 pandas dataframe 来加载接收到的有效载荷,当格式化时它没有按照我的意愿格式化,我的代码示例:

import pandas as pd

df = pd.DataFrame([{'A': 2.5e-07, 'B': 2.5e-05, 'C': 2.5e-04, 'D': 0.0001, 'E': 0.01}])

pd.options.display.float_format = '{:f}'.format
print(df.to_string())

pd.set_option('display.float_format', str)
print(df.to_string())

The output: output:

         A        B        C        D        E
0 0.000000 0.000025 0.000250 0.000100 0.010000

        A       B       C      D    E
0 2.5e-07 2.5e-05 0.00025 0.0001 0.01

what I would like to get:我想得到什么:

        A       B       C      D    E
0 0.0000025 0.000025 0.00025 0.0001 0.01

We can use np.format_float_positional :我们可以使用np.format_float_positional

import numpy as np
import pandas as pd

pd.set_option('display.float_format', np.format_float_positional)

df = pd.DataFrame([
    {'A': 2.5e-07, 'B': 2.5e-05, 'C': 2.5e-04, 'D': 0.0001, 'E': 0.01}
])

print(df.to_string())

Or with an option_context或者使用option_context

import numpy as np
import pandas as pd

df = pd.DataFrame([
    {'A': 2.5e-07, 'B': 2.5e-05, 'C': 2.5e-04, 'D': 0.0001, 'E': 0.01}
])

with pd.option_context('display.float_format', np.format_float_positional):
    print(df.to_string())

Both Produce:两者都产生:

           A        B       C      D    E
0 0.00000025 0.000025 0.00025 0.0001 0.01

You can alter the number of floating point decimals but this is applied to all values.您可以更改浮点小数位数,但这适用于所有值。

In [61]: df = pd.DataFrame([{'A': 2.5e-07, 'B': 2.5e-05, 'C': 2.5e-04, 'D': 0.0001, 'E': 0.01}])

In [62]: formats = {"A": "{:,.8f}","B": "{:,.6f}", "C": "{:,.5f}", "D": "{:,.4f}", "E": "{:,.2f}"}

In [63]: for col, f in formats.items():
    ...:     df[col] = df[col].map(lambda x: f.format(x))
    ...: 

In [64]: df
Out[64]: 
            A         B        C       D     E
0  0.00000025  0.000025  0.00025  0.0001  0.01

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM