首页 > 解决方案 > 将带小数的浮点数转换为不带小数点的字符串 Python 3.7

问题描述

努力将浮点数 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)

标签: python-3.xpandasdataformat

解决方案


你可以像这样简单地做到这一点:

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

推荐阅读