Python:使用上标指数的科学计数法

3
我试图使用基数为10的指数科学计数法格式化数字,例如将0.00123写成1.23x10–3,使用Python 3。
我找到了这个很棒的函数,它打印1.23x10^-3,但是如何将插入符指数替换为上标呢?
def sci_notation(number, sig_fig=2):
    ret_string = "{0:.{1:d}e}".format(number, sig_fig)
    a,b = ret_string.split("e")
    b = int(b)         # removed leading "+" and strips leading zeros too.
    return a + "x10^" + str(b)

print(sci_notation(0.001234, sig_fig=2))      # Outputs 1.23x10^-3

该函数是从https://stackoverflow.com/a/29261252/8542513修改而来。
我尝试结合https://dev59.com/D2oy5IYBdhLWcg3wScJB#8651690的答案格式化上标,但我不确定sympy如何处理变量。
from sympy import pretty_print as pp, latex
from sympy.abc import a, b, n

def sci_notation(number, sig_fig=2):
  ret_string = "{0:.{1:d}e}".format(number, sig_fig)
  a,b = ret_string.split("e")
  b = int(b)             #removed leading "+" and strips leading zeros too.
  b = str(b)
  expr = a + "x10"**b    #Here's my problem
  pp(expr)               # default
  pp(expr, use_unicode=True)
  return latex(expr)

print(latex(sci_notation(0.001234, sig_fig=2))) 

这会返回:TypeError: 不支持使用 ** 或 pow() 运算符的类型为 'str' 和 'int' 的操作数。

你在哪里打印?并非所有东西都支持上标(例如控制台)。 - Ma0
我想将该函数应用于pandas数据框。来自https://dev59.com/D2oy5IYBdhLWcg3wScJB#8651690的代码在Jupyter Notebook中打印指数。 - Marla
它只是在不同的行中打印 n,并使其看起来像一个(格式不良的)指数。 - Ma0
你想要什么结果?你想要数字为0.001234还是1.23x10^-3。 - Tobias Wilfert
我希望以上标形式显示10的指数(请参见问题的第一行)。 - Marla
3个回答

3
这里有一个简单的解决方案:
def SuperScriptinate(number):
  return number.replace('0','⁰').replace('1','¹').replace('2','²').replace('3','³').replace('4','⁴').replace('5','⁵').replace('6','⁶').replace('7','⁷').replace('8','⁸').replace('9','⁹').replace('-','⁻')

def sci_notation(number, sig_fig=2):
    ret_string = "{0:.{1:d}e}".format(number, sig_fig)
    a,b = ret_string.split("e")
    b = int(b)         # removed leading "+" and strips leading zeros too.
    return a + "x10^" + SuperScriptinate(str(b))

1
你的‘-1’看起来像是‘_1’, 但是你第一个函数定义时忘记了加冒号。有没有‘baby’的‘-’? - Ma0
2
我已经修复了你指出的问题,@Ev.Kounis,谢谢。这里有一个小减号 -。它是 - Richard

2

scinot这个包可以格式化科学计数法的数字

import scinot as sn
a=4.7e-8
print(scinot.format(a))

4.7 × 10⁻⁸

或者在字符串中

print('The value is {0:s}'.format(scinot.format(a)))

The value is 4.7 × 10⁻⁸

0

我理解你的主要问题是如何用上标替换插入符号?

如果你在Jupyter笔记本中使用Python,有一个简单的方法:

  from IPython.display import display, Math, Latex

  # if the number is in scientific format already
  display(Math('2.14e-6'.replace('e', r'\times 10^{') + '}'))

  # if it is not:
  d = "%e" % (number)
  # then use the above form: display(Math(d.replace('e', r'\times ...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接