如何从字符串中删除十进制后的零


问题内容

我有一个带有对象列的数据框,让它说col1,其值类似于:1.00、1、0.50、1.54

我希望输出如下:1,1,0.5,1.54基本上,如果小数点后没有任何数字,则除去小数点后的零。请注意,我需要回答数据框。pd.set_option和round对我不起作用。


问题答案:

如果想转换整形和浮点数字为字符串没有尾随0使用这种具有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