简体   繁体   English

如何计算 dataframe 中的尾随零而不计算小数点后的零?

[英]How can I count trailing zeros in a dataframe without counting zero after the decimal point?

I am trying to calculate the trailing zeros in a dataframe and add them as a new column.我正在尝试计算 dataframe 中的尾随零并将它们添加为新列。 However my code:但是我的代码:

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))

is giving me 1 for values that have a zero at the end as well as for numbers that have a trailing decimal point of zero.对于末尾为零的值以及尾随小数点为零的数字,给我 1。 I only want the prior.我只想要之前的。

Bloomberg Code彭博代码 index...指数... Trade price交易价格 Trade price round交易价格回合
90 90 ATCOB SS Equity ATCOB SS 股票 149... 149... 254.6 254.6 0 0
91 91 AZN SS Equity AZN SS 股票 150... 150... 613 613 1 1
92 92 AZN SS Equity AZN SS 股票 151... 151... 610 610 1 1
93 93 AZN SS Equity AZN SS 股票 152... 152... 610 610 1 1
94 94 AZN SS Equity AZN SS 股票 153... 153... 610 610 1 1
95 95 BOL SS Equity BOL SS 股票 154... 154... 184.5 184.5 0 0
96 96 BOL SS Equity BOL SS 股票 155... 155... 182.1 182.1 0 0
97 97 BOL SS Equity BOL SS 股票 156... 156... 182.1 182.1 0 0
98 98 BOL SS Equity BOL SS 股票 157... 157... 182.1 182.1 0 0
99 99 ELUXB SS Equity ELUXB SS 股票 158... 158... 228 228 1 1

As you can see with index number 99 it still counts the floating point whilst index number 94 has exactly what I want.正如您在索引号 99 中看到的那样,它仍然计算浮点数,而索引号 94 正是我想要的。 What am I doing wrong?我究竟做错了什么?

Doing something like this with another column I have would help:用我的另一列做这样的事情会有所帮助:

dataset['Trade price int'] = 1 if dataset['Trade price float'] == 0 else 0

but of course I get the error:但当然我得到了错误:

ValueError: The truth value of a Series is ambiguous. ValueError:Series 的真值不明确。 Use a.empty, a.bool(), a.item(), a.any() or a.all().使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

How can I apply any() or some other function to this?我如何将 any() 或其他一些 function 应用于此?

Have you tried the int() function so that you can count the trailing zeros from the integer number and not the float one?您是否尝试过 int() function 以便您可以计算 integer 数字中的尾随零而不是浮点数?

I've got the answer.我已经得到了答案。 Since the trailing zero stops at the decimal you need to use float then strip both the zero and the decimal point then the zeros again.由于尾随零在小数点处停止,您需要使用浮点数,然后去除零和小数点,然后再次去除零。 However this adds two to the number at the end so you need to add an if statement to remove 2 if the difference is greater than zero like this:但是,这会在末尾添加 2,因此如果差异大于零,则需要添加 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM