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

问题描述 投票:1回答:5

我有一个带有对象列的数据框让我们说col1,其值如:1.00,1,0.50,1.54

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

python pandas
5个回答
0
投票

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

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

0
投票

一个快速而肮脏的解决方案是使用"%g" % value,它将浮动1.5转换为1.51.0转换为1等等。负面的副作用是大数字将用4.44e+07等科学记数法表示。


0
投票

取自this Stackoverflow answer,我想你想改变大熊猫的显示精度,如下:

pd.set_option('precision', 0)

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']

0
投票

我认为这样的事情应该有效:

if val.is_integer() == True :
    val = int(val)
elif val.is_float() == True :
    val = Decimal(val).normalize()

假设val是数据框列中的float值。您只需将值转换为整数。对于浮点值,您可以减少额外的零。

© www.soinside.com 2019 - 2024. All rights reserved.