When i try to change the type from string to float using this line of code :
df_outer['Revenue Change'] =
df_outer['Revenue Change'].str.rstrip("%").astype(float)/100
I have the error on the screenshot due to the '-'.
I dont want to delete the minus symbol because i need the negative numbers.
How can i make this work ?
For instance i want the -5.20% to be -0.0520 .
CodePudding user response:
I couldn't reproduce your error while converting the string to float. So I'm not sure about that part. However, to achieve what you want here's what you can do
rev_change = df_outer['Revenue Change'] # just to make it a bit compact
df_outer['Revenue Change'] = [float(i.strip('%'))/100 for i in rev_change]
However, if you still are having the negative sign issue, here's the second solution
rev_change = df_outer['Revenue Change']
df_outer['Revenue Change'] = [float(i.strip('%'))/100 if i[0] != '-' else
-1*float(i[1:].strip('%'))/100 for i in rev_change]
CodePudding user response:
I've put the same values as a list of string and I'm able to do the same with typecasting. Instead of .str
or .float
use str()
or float()
.
I've attached a screenshot of the code and the output below.
This way we wouldn't have to check for the first character being a minus or not using string operations, python will do it for us.
The code -->
revenueChange = ['3.00%', '-5.25%']
for i in revenueChange:
res = float(i.strip('%'))/100
print(res)