我有一个带有对象列的数据框让我们说col1,其值如:1.00,1,0.50,1.54
我希望得到如下所示的输出:1,1,5,1.54基本上,如果在零之后没有任何数字,则在十进制值之后删除零。请注意我需要数据帧的答案。 pd.set_option和round对我不起作用。
如果想要将整数和浮点数转换为没有尾随0
的字符串,请使用this和map
或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
一个快速而肮脏的解决方案是使用"%g" % value
,它将浮动1.5
转换为1.5
但1.0
转换为1
等等。负面的副作用是大数字将用4.44e+07
等科学记数法表示。
取自this Stackoverflow answer,我想你想改变大熊猫的显示精度,如下:
pd.set_option('precision', 0)
怎么样的str.rstrip
方法。像这样(假设你的字符串在列表中):
a = ["1.00", "1" ,"0.50", "1.50"]
b = [e.rstrip('.0') for e in a]
>>> ['1', '1', '0.5', '1.5']
我认为这样的事情应该有效:
if val.is_integer() == True :
val = int(val)
elif val.is_float() == True :
val = Decimal(val).normalize()
假设val
是数据框列中的float
值。您只需将值转换为整数。对于浮点值,您可以减少额外的零。