【问题标题】:pandas convert big int to string avoid scientific notation [duplicate]熊猫将大整数转换为字符串避免科学记数法[重复]
【发布时间】:2020-07-24 00:40:05
【问题描述】:

我有一个来自 csv 文件的数据框,该文件使用 pandas.read_csv() 方法加载,如下所示:

                   id  col
0 1151377158377549824 row0
1 1151346166619103232 row1
2 1151737502769827840 row2

列的类型是:

df.dtypes
out:
id        float64
col       object

我想将 id 的类型更改为字符串,但使用 astype(str) 或 apply(str),将其转换为科学计数法后:

                      id  col
0 1.1513771583775498e+18 row0
1 1.1513461666191032e+18 row1
2 1.1517375027698278e+18 row2

转换后我应该怎么做才能避免科学记数法?

【问题讨论】:

  • id 列不是浮点数,您应该阻止 pandas 读取它。如果您想将其作为字符串,请使用read_csvdtype 参数将其作为对象读取。
  • 您的 id 列 dtype 被错误地推断为 float,正如 cel 所说。使用显式数据类型
  • 也许我需要这些列像字符串一样浮动,然后呢?
  • python 自动将 id 列解释为浮点数,因此您可以获得科学记数法。因此,在读取 csv 时指定列的数据类型 pd.read_csv("data.csv", dtype={'id': 'Int64'}) 上面的行将在读取 df 时解决问题

标签: python pandas


【解决方案1】:

您可以先转换为 Int64,然后再转换为字符串:

df['id'] = df['id'].astype("Int64").astype(str)
df

输出:

【讨论】:

    猜你喜欢
    • 2014-12-23
    • 2019-04-22
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    相关资源
    最近更新 更多