【问题标题】:scientific notation not being displayed in dataframe科学记数法未显示在数据框中
【发布时间】:2022-01-23 17:52:30
【问题描述】:

我想在表格中显示列向量,并决定为此使用 pandas.DataFrame。 向量中的元素具有科学记数法,我不希望符号改变。 以下是向量:

err=np.array([[0.5671],[0.4328],[0.4555e-01],[0.3305e-02], [0.2707e-04], [0.1660e-7]])
a= (1+np.sqrt(5))/2
ratio1=np.array(abs(err[1:6]/err[0:5]))
ratio2=np.array(abs(err[1:6]/err[0:5]**a))
ratio3=np.array(abs(err[1:6]/err[0:5]**2))

我做了以下矩阵:

table=np.hstack((ratio1, ratio2, ratio3))
[[7.63181097e-01 1.08361327e+00 1.34576106e+00]
 [1.05244917e-01 1.76598890e-01 2.43172174e-01]
 [7.25576290e-02 4.89533998e-01 1.59292270e+00]
 [8.19062027e-03 2.79610288e-01 2.47825122e+00]
 [6.13224972e-04 4.07847058e-01 2.26533052e+01]]

此时符号是我想要的,但是当我使用 pandas.DataFrame 打印它时,我失去了科学记数法,我不明白为什么。

pandas.DataFrame(table, columns=["ratio 1","ratio 2", "ratio 3"])
   ratio 1   ratio 2    ratio 3
0  0.763181  1.083613   1.345761
1  0.105245  0.176599   0.243172
2  0.072558  0.489534   1.592923
3  0.008191  0.279610   2.478251
4  0.000613  0.407847  22.653305

我在使用这种方法时也得到了完全相同的结果:

table={}
table["ratio1"]=ratio1[:,0].tolist()
table["ratio2"]=ratio2[:,0].tolist()
table["ratio3"]=ratio3[:,0].tolist()
print(pandas.DataFrame(table, index=[1,2,3,4,5]))

有人知道这是什么原因吗?

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    您可以在创建数据框之前使用 pd.set_option() 来设置您需要的格式。

    err=np.array([[0.5671],[0.4328],[0.4555e-01],[0.3305e-02], [0.2707e-04], [0.1660e-7]])
    a= (1+np.sqrt(5))/2
    ratio1=np.array(abs(err[1:6]/err[0:5]), dtype="float")
    ratio2=np.array(abs(err[1:6]/err[0:5]**a), dtype="float")
    ratio3=np.array(abs(err[1:6]/err[0:5]**2), dtype="float")
    table=np.hstack((ratio1, ratio2, ratio3))
    
    
    pd.set_option('display.float_format','{:.8e}'.format)
    df = pd.DataFrame(table, columns=["ratio 1","ratio 2", "ratio 3"])
    

    输出:

             ratio 1        ratio 2        ratio 3
    0 7.63181097e-01 1.08361327e+00 1.34576106e+00
    1 1.05244917e-01 1.76598890e-01 2.43172174e-01
    2 7.25576290e-02 4.89533998e-01 1.59292270e+00
    3 8.19062027e-03 2.79610288e-01 2.47825122e+00
    4 6.13224972e-04 4.07847058e-01 2.26533052e+01
    

    额外说明:这也会影响您的代码中可能出现的其他数据帧。如果你想重置科学记数法,你可以使用以下代码来设置 float_format:pd.reset_option('display.float_format')

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-21
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2015-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多