python pandas:如何在乳胶中格式化10的幂数

时间:2016-12-15 06:36:38

标签: pandas latex

我使用pandas生成一些大/小数字的大型LaTex表:

No

其中" outfile"只是一个数字表(3列)...我怎样才能将outfile中的数字格式化为:

df = pd.DataFrame(np.array(outfile),columns=['Halo','$r_{v}$','etc'])
df.to_latex("uvFlux_table_{:.1f}.tex".format(z))

- 就像你在科学出版物中看到的......与默认

相比
$1.5x10^{12}$  &   $1.5x10^{12}$  &  $1.5x10^{-12}$

...

3 个答案:

答案 0 :(得分:1)

定义

def format_tex(float_number):
    exponent = np.floor(np.log10(float_number))
    mantissa = float_number/10**exponent
    mantissa_format = str(mantissa)[0:3]
    return "${0}\times10^{df = pd.DataFrame({'col':[12345.1200000,100000000]})
df.applymap(lambda x:format_tex(x))
}$"\
           .format(mantissa_format, str(int(exponent)))

您可以在数据框上应用该函数(并应用于系列)

-o

这给了jupyter笔记本中的tex输出。 请注意,转义可能在这里很棘手。其他更快的解决方案在这里?

答案 1 :(得分:1)

谢谢@ Quickbeam2k1的答案。我已经扩展到处理0和负数:

# Define function for string formatting of scientific notation
def exp_tex(float_number):
    """
    Returns a string representation of the scientific
    notation of the given number formatted for use with
    LaTeX or Mathtext.
    """
    neg = False
    if float_number == 0.0:
        return r"$0.0"
    elif float_number < 0.0:
        neg = True

    exponent = np.floor(np.log10(abs(float_number)))
    mantissa = float_number/10**exponent
    if neg:
        mantissa = -mantissa
    mantissa_format = str(mantissa)[0:3]
    return "${0}\\times10^{ÿþ}$"\
           .format(mantissa_format, str(int(exponent)))

答案 2 :(得分:1)

我认为最好不要在这里重新发明轮子,而要使用python提供给我们的float格式化工具:

def float_exponent_notation(float_number, precision_digits, format_type="g"):
    """
    Returns a string representation of the scientific
    notation of the given number formatted for use with
    LaTeX or Mathtext, with `precision_digits` digits of
    mantissa precision, printing a normal decimal if an
    exponent isn't necessary.
    """
    e_float = "{0:.{1:d}{}}".format(float_number, precision_digits, format_type)
    if "e" not in e_float:
        return "${}$".format(e_float)
    mantissa, exponent = e_float.split("e")
    cleaned_exponent = exponent.strip("+")
    return "${0} \\times 10^{"g"}$".format(mantissa, cleaned_exponent)

此版本对于零,负等是安全的。它会正确舍入(其他任何一个都不做!)。它还提供了使用.to_latex格式代码的选项,如果小数点位于您设置的精度范围内,则该代码将使用小数显示数字。

此外,如果您还传递escape=False,则可以将它们作为格式器传递给{{1}}方法。我有一个格式化程序包装程序,该程序进行类型检查并在遇到字符串时进行转义。