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%
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})
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.