如何从字符串中删除小数点后的零 [英] how to remove zeros after decimal from string remove all zero after dot
本文介绍了如何从字符串中删除小数点后的零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有对象列的数据框,可以说col1,其值类似于: 1.00, 1, 0.50, 1.54
I have data frame with a object column lets say col1, which has values likes: 1.00, 1, 0.50, 1.54
我想要类似以下的输出: 1, 1, 0.5, 1.54 基本上,如果小数点后没有任何数字,则除去小数点后的零.请注意,我需要回答数据框. pd.set_option和round对我不起作用.
I want to have the output like the below: 1, 1, 0.5, 1.54 basically, remove zeros after decimal values if it does not have any digit after zero. Please note that i need answer for dataframe. pd.set_option and round don't work for me.
推荐答案
如果要转换整数并将数字浮点数转换为没有尾随0
的字符串,请使用此与map
或apply
:
If want convert integers and floats numbers to strings with no trailing 0
use this with map
or apply
:
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
这篇关于如何从字符串中删除小数点后的零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文