我正在尝试计算数据帧中的尾随零,并将它们添加为新列。然而,我的代码:
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。我只想要之前的。
90 | ATCOB SS股权 | 149 | 254.6 |
91 | 613 | ||
92 | 610 | ||
93 | 610 | ||
94 | AZN SS股票 | 153 | 610 |
95 | 184.5 | ||
96 | 182.1 | ||
97 | 182.1 | ||
98 | 182.1 | ||
99 | ELUXB SS股票 | 158 | 228 |
您是否尝试过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)