4

I cannot convert data types in my dataframe to float from string (they are numerical values as string or empty strings):

calcMeanPrice_df = dessertApples_df.iloc[:, 5:17]      #slice of columns

for col  in calcMeanPrice_df:                          #iterate columns
    pd.to_numeric(col, errors = 'coerce')              #attempt to convert to numeric

calcMeanPrice_df.dtypes                                #return data column types

Out[21]:
4     object
5     object
6     object
7     object
8     object
9     object
10    object
11    object
12    object
13    object
14    object
15    object
dtype: object

What am i doing wrong here?

1
  • 1
    to_numeric does not work inplace, you need to assign its return value someplace Commented Dec 28, 2017 at 0:57

1 Answer 1

15

Hypothetical DataFrame:

df = pd.DataFrame({'a':['5','10'], 'b':['9','7']})

Current data types:

In [391]: df.dtypes
Out[391]: 
a    object
b    object

Convert the entire df columns to numeric:

df = df.apply(pd.to_numeric)

Result:

In [393]: df.dtypes
Out[393]: 
a    int64
b    int64

Convert only select columns to numeric:

In [396]: df = pd.DataFrame({'a':['5','10'], 'b':['9','7']})
In [397]: df['a'] = df['a'].apply(pd.to_numeric)
In [398]: df.dtypes
Out[398]: 
a     int64
b    object
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.