I am trying to calculate the trailing zeros in a dataframe and add them as a new column. 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. I only want the prior.
Bloomberg Code | index... | Trade price | Trade price round | |
---|---|---|---|---|
90 | ATCOB SS Equity | 149... | 254.6 | 0 |
91 | AZN SS Equity | 150... | 613 | 1 |
92 | AZN SS Equity | 151... | 610 | 1 |
93 | AZN SS Equity | 152... | 610 | 1 |
94 | AZN SS Equity | 153... | 610 | 1 |
95 | BOL SS Equity | 154... | 184.5 | 0 |
96 | BOL SS Equity | 155... | 182.1 | 0 |
97 | BOL SS Equity | 156... | 182.1 | 0 |
98 | BOL SS Equity | 157... | 182.1 | 0 |
99 | ELUXB SS Equity | 158... | 228 | 1 |
As you can see with index number 99 it still counts the floating point whilst index number 94 has exactly what I want. 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. Use a.empty, a.bool(), a.item(), a.any() or a.all().
How can I apply any() or some other function to this?
Have you tried the int() function so that you can count the trailing zeros from the integer number and not the float one?
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:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.