-1

I am importing a csv file into python with the pandas package.

SP = pd.read_csv('S&P500 (5year).csv')

When I go to use the pct_change() operand, it is unable to process the values as they have been saved with the type 'str'.

I have tried using the .astype(float) method and it returns an error could not convert string to float: '1805.51' The 'Adj Close**' are type str and I need them as type float

Date    Open    High    Low Close*  Adj Close** Volume
0   11/1/2013   1,758.70    1,813.55    1,746.20    1,805.81    1,805.81    63,628,190,00
1   12/1/2013   1,806.55    1,849.44    1,767.99    1,848.36    1,848.36    64,958,820,000.00
2   1/1/2014    1,845.86    1,850.84    1,770.45    1,782.59    1,782.59    75,871,910,000.00
3   2/1/2014    1,782.68    1,867.92    1,737.92    1,859.45    1,859.45    69,725,590,000.00
4   3/1/2014    1,857.68    1,883.97    1,834.44    1,872.34    1,872.34    71,885,030,000.00
tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • Please show us a couple of lines from the file. Do you have multiple lines of headers? – Tim Roberts Sep 21 '21 at 02:26
  • I changed your data to a code block... I that the original CSV file or perhaps some display of the dataframe? – tdelaney Sep 21 '21 at 02:39
  • _it returns an error_. You should post some small sample code and the traceback. "an error" isn't enough. This is likely a duplicate of https://stackoverflow.com/questions/22137723/convert-number-strings-with-commas-in-pandas-dataframe-to-float – tdelaney Sep 21 '21 at 02:45

1 Answers1

0

Try adding dtype and thousands into read_csv function. Replace the column_name in the example with the column you need to convert to float. As csv is split by commas, you need to add the thousands parameter when reading csv.

Example:

SP = pd.read_csv('S&P500 (5year).csv', thousands=',', dtype={'column_name': float})
Raymond Toh
  • 779
  • 1
  • 8
  • 27