0

In my CSV file, the % Return column is currently all strings. How can I remove the % symbol and make all the values a float?

Example of CSV file:

Date,Cash,Cash Interest,Margin Cost,Net Worth,% Return
9/16/2019,"$45.96 ",N/A,N/A,"$36.94 ",38.94%
9/13/2019,"$27.50 ",N/A,N/A,"$39.88 ",39.02%
9/12/2019,"$27.50 ",N/A,N/A,"$38.77 ",39.56%
9/11/2019,"$27.50 ",N/A,N/A,"$33.06 ",39.13%
9/10/2019,"$27.50 ",N/A,N/A,"$34.78 ",35.47%
9/9/2019,"$27.50 ",N/A,N/A,"$35.81 ",34.69%
9/6/2019,"$27.50 ",N/A,N/A,"$32.31 ",33.55%
9/5/2019,"$27.50 ",N/A,N/A,"$35.24 ",33.61%
9/4/2019,"$11.07 ",N/A,N/A,"$30.04 ",30.91%
1
  • please, share what you have tried - ![df['% Return'] = df['% Return'].str.extract('\d+.\d+').astype(float)] Commented Aug 6, 2020 at 8:44

1 Answer 1

1

You can define a function to convert percent values to float. Like this:

import pandas as pd

# define your function to convert
def percent_to_float(x):
    return float(x.strip('%'))/100

#read your csv file, 'col' is your column with percent values
df = pd.read_csv('data.csv', converters={'col':percent_to_float})
Sign up to request clarification or add additional context in comments.

3 Comments

What is the purpose of 'col'?
Hey, I edited the answer. col is your column with percent values.
Thank you so much, this worked. For some reason, the apply function wasn't working. Do you know why?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.