【问题标题】:Convert Float with decimal to string without decimal Python 3.7将带小数的浮点数转换为不带小数点的字符串 Python 3.7
【发布时间】:2021-08-06 14:09:30
【问题描述】:

努力将浮点数 12345678.0 转换为字符串 12345678 经过我在 SO 中找到的几种不同的解决方案,但似乎无法到达终点,小数点不会下降。

这是我尝试过的

df["variable"]= df["variable"].astype(str)
df["variable"]= df["variable"].astype(int).astype(str)

# old lambda solution 
cols = ['variable']
for col in cols:
   df[col] = df[col].apply(lambda x: int(x) if x == x else "")

# convert int to string 
df["variable"] = df["variable"].astype(str)

【问题讨论】:

  • 您可以使用.astype('Int64'),如果您无法将您的系列安全地转换为int,则会引发错误,同时还允许您在该列中存储NaN

标签: python-3.x pandas dataformat


【解决方案1】:

你可以这样做:

df['variable'] = df['variable'].astype(int, errors = 'ignore').astype(str)

【讨论】:

  • 我看到你写的你已经试过了。你遇到了什么错误?
  • 因为他们正在检查if x == x,几乎可以肯定是因为他们在列中有NaN(这就是为什么所有int首先都变成浮动的),而你不能int(np.NaN)
  • @gtomer 该解决方案导致第二个错误 ValueError: invalid literal for int() with base 10: ''
  • 所以我们可以调试它,请将它分成两行:df['variable'] = df['variable'].astype(int) 然后 df['variable'] = df[ '变量'].astype(str)
  • 运行转换为 int 会产生此错误 ValueError: invalid literal for int() with base 10: ''
【解决方案2】:

这是你的 lambda 函数

lambda x: str(int(x))

【讨论】:

    猜你喜欢
    • 2018-07-07
    • 2019-06-03
    • 1970-01-01
    • 1970-01-01
    • 2012-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多