首页 > 解决方案 > 如何从字符串中删除小数点后的零删除点后的所有零

问题描述

我有一个带有对象列的数据框,可以说 col1,它的值如下:1.00、1、0.50、1.54

我希望输出如下所示:1、1、0.5、1.54 基本上,如果零后没有任何数字,则删除十进制值后的零。请注意,我需要数据框的答案。pd.set_option 和 round 对我不起作用。

标签: pythonpandas

解决方案


如果想要将整数和浮点数转换为没有尾随的字符串,0使用or :mapapply

df = pd.DataFrame({'col1':[1.00, 1, 0.5, 1.50]})

df['new'] = df['col1'].map('{0:g}'.format)
#alternative solution
#df['new'] = df['col1'].apply('{0:g}'.format)
print (df)
   col1  new
0   1.0    1
1   1.0    1
2   0.5  0.5
3   1.5  1.5

print (df['new'].apply(type))
0    <class 'str'>
1    <class 'str'>
2    <class 'str'>
3    <class 'str'>
Name: new, dtype: object

推荐阅读