【问题标题】:Logic of display numbers in a dataframe数据框中显示数字的逻辑
【发布时间】:2019-12-16 05:33:51
【问题描述】:

我在 win10 上使用 jupyter notebook 时有以下数据框。

d = {'col1': [1000000, 200000000000000], 'col2': [3, 4]}
df2 = pd.DataFrame(data=d)
df2.describe()

导致以下输出:

         col1           col2
count   2.000000e+00    2.000000
mean    1.000000e+14    3.500000
std     1.414214e+14    0.707107
min     1.000000e+06    3.000000
25%     5.000000e+13    3.250000
50%     1.000000e+14    3.500000
75%     1.500000e+14    3.750000
max     2.000000e+14    4.000000

我知道这只是一个“光学”问题,但不知何故我不喜欢它,当第一行没有相同的数字格式时,比较它并不容易。有没有办法避免这种显示,而是有输出,不知何故python对列使用相同的格式而不是对行?:

         col1           col2
count   2.000000        2.000000
mean    1.000000e+14    3.500000
std     1.414214e+14    0.707107
min     1.000000e+06    3.000000
25%     5.000000e+13    3.250000
50%     1.000000e+14    3.500000
75%     1.500000e+14    3.750000
max     2.000000e+14    4.000000

或者是否有可能每行而不是列具有相同的格式?

我可以只更改所有的浮动显示吗?这样:Customized float formatting in a pandas DataFrame,还是pandas能聪明点?

【问题讨论】:

标签: python pandas


【解决方案1】:

尝试类似:

import pandas as pd
pd.options.display.float_format = '{:,.2e}'.format
d = {'col1': [1000000, 200000000000000], 'col2': [3, 4]}
df2 = pd.DataFrame(data=d)
df2.describe()

应该给:

          col1     col2
count 2.00e+00 2.00e+00
mean  1.00e+14 3.50e+00
std   1.41e+14 7.07e-01
min   1.00e+06 3.00e+00
25%   5.00e+13 3.25e+00
50%   1.00e+14 3.50e+00
75%   1.50e+14 3.75e+00
max   2.00e+14 4.00e+00

请注意,您可以自定义 pandas 行为的某些方面以及其他与显示相关的选项。查看可用选项here

【讨论】:

【解决方案2】:
pd.options.display.float_format = lambda x: f'{x:<12.6e}' if x < .1 or x >= 10 else f'{x:<12.6f}'

          col1         col2
count 2.000000     2.000000    
mean  1.000000e+14 3.500000    
std   1.414214e+14 0.707107    
min   1.000000e+06 3.000000    
25%   5.000000e+13 3.250000    
50%   1.000000e+14 3.500000    
75%   1.500000e+14 3.750000    
max   2.000000e+14 4.000000

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-23
    • 2020-09-23
    • 1970-01-01
    相关资源
    最近更新 更多