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:
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:
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
CodePudding user response:
We can use 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
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
CodePudding user response:
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
CodePudding user response:
pd.set_option('display.float_format', lambda x: '%.6f'%x)
CodePudding user response:
Try this:
>>> df.apply(lambda x : ('%.9f' % x).rstrip('0')).to_frame().T
A B C D E
0 0.00000025 0.000025 0.00025 0.0001 0.01