如何在不计算小数点后零的情况下计算数据帧中的尾随零



我正在尝试计算数据帧中的尾随零,并将它们添加为新列。然而,我的代码:

dataset['Trade price round'] = dataset['Trade Price'].apply(lambda x: len(str(x))) - dataset['Trade Price'].apply(lambda x: len(str(x).rstrip('0')))
print(dataset.tail(10))

对于末尾有零的值以及尾部小数点为零的数字,给我1。我只想要之前的。

01110001
90ATCOB SS股权149254.6
91613
92610
93610
94AZN SS股票153610
95184.5
96182.1
97182.1
98182.1
99ELUXB SS股票158228

您是否尝试过int((函数,以便从整数而不是浮点数中计算尾随零?

我得到了答案。由于后面的零停在小数点,您需要使用float,然后去掉零和小数点,然后再去掉零。然而,这会在末尾的数字上加上两个,所以如果差值大于零,则需要添加一个if语句来删除2,如下所示:

dataset['Trade price round'] = dataset['Trade Price'].apply(lambda x: len(str(float(x))) - len(str(float(x)).rstrip('0').rstrip('.').rstrip('0')) - 2 if len(str(float(x))) - len(str(float(x)).rstrip('0').rstrip('.').rstrip('0')) > 0 else 0)

相关内容

最新更新