0

I'm trying to convert a column of strings to float after reading from a csv into pandas dataframe. Unfortunately, I get the following error:

ValueError: could not convert string to float: size

The code I am using is the following:

df['size'] = df['size'].apply(lambda x:float(x))

Any ideas?

A sample of my dataframe is below:

>>> df.head(4)

                         localtime  symbol exchange   price  size
NaN                      localtime  symbol     exch   price  size
 0   2017-08-01 13:30:00.130514241    AAPL     NSDQ  149.08    71
 1   2017-08-01 13:30:00.148672863    AAPL     NSDQ  149.05    33
 2   2017-08-01 13:30:00.148695312    AAPL       BX  149.05    45
5
  • 1
    Can you look into values for size series. Looks like it has string size Commented Apr 17, 2018 at 18:09
  • Can you post a small sample of your dataframe? Commented Apr 17, 2018 at 18:12
  • they are all numeric values within the csv Commented Apr 17, 2018 at 18:12
  • tks chrisz, just did Commented Apr 17, 2018 at 18:14
  • It doesn't look like your csv was read correctly. It looks like the columns names were also read into the first row of the dataframe. Commented Apr 17, 2018 at 18:30

1 Answer 1

1

Try using pd.to_numeric

df['size'] =  pd.to_numeric(df['size'], errors='coerce')

or:

df['size'] = df['size'].astype(float)

From the data you have posted looks like you have “size” in your column. That is why you are getting the error. You can use skiprows to skip any unwanted row.

Sign up to request clarification or add additional context in comments.

Comments

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.