简体   繁体   English

禁止 Pandas 中的科学记数法 *不*改变精度

[英]Suppress scientific notation in Pandas *without* altering precision

Is there a way to suppress scientific notation in Panda's outputs without forcing a particular precision across all columns?有没有办法在 Panda 的输出中抑制科学记数法而不强制所有列都具有特定的精度?

So that a data frame:这样一个数据框:

import pandas as pd

df = pd.DataFrame({"a": [0.01, 0.02, 0.03], "b": [0.0000001, 0.0000002, 0.0000003]})

df.to_csv(
    "df.csv",
    index=False,
)

That initially would be outputted as:最初将输出为:

a一个 b b
0.01 0.01 1.00E-07 1.00E-07
0.02 0.02 2.00E-07 2.00E-07
0.03 0.03 3.00E-07 3.00E-07

Instead becomes my desired output:而是变成了我想要的 output:

a一个 b b
0.01 0.01 0.0000001 0.0000001
0.02 0.02 0.0000002 0.0000002
0.03 0.03 0.0000003 0.0000003

Many questions about suppressing scientific notation in Pandas'.to_csv results have already been asked , but all of the answers involve specifying an arbitrary precision. 已经提出了许多关于在 Pandas'.to_csv 结果中抑制科学记数法的问题,但所有答案都涉及指定任意精度。

For instance, setting float_format="%.7f" in df.to_csv forces 7 significant digits for all float columns and numbers (and so does round(7) , of course).例如,在df.to_csv中设置float_format="%.7f"会强制所有浮点列和数字使用 7 个有效数字(当然, round(7)也是如此)。

This would lead to the following output, which I don't want:这将导致以下 output,这是我不想要的:

a一个 b b
0.0100000 0.0100000 0.0000001 0.0000001
0.0200000 0.0200000 0.0000002 0.0000002
0.0300000 0.0300000 0.0000003 0.0000003

(I also tried using np.format_float_positional as suggested here , but had no luck.) (我也尝试按照这里的建议使用np.format_float_positional ,但没有运气。)

Implement np.format_float_positiona l on a series.在系列上实施np.format_float_positiona If done on df, you will be forced to iterate which can be quite computationally expensive.如果在 df 上完成,您将被迫进行迭代,这在计算上可能非常昂贵。

Pd.Series Pd系列

df['b'] =[(lambda x: np.format_float_positional(x))(x) for x in df['b']]

or simply as suggested by @user2357112 supports Monica或者只是按照@user2357112 的建议支持莫妮卡

df['b'] =[np.format_float_positional(x) for x in df['b']]

Def function Lets try putting this in def function Def function让我们尝试将其放入 def function

import numpy as np

def format_float(df):
    
    cols=list(df.columns)
    for col in cols:
        df[col]=[np.format_float_positional(x) for x in df[col]]
        
    return df

format_float(df)

outcome结果

 a          b
0  0.01  0.0000001
1  0.02  0.0000002
2  0.03  0.0000003

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM