Converting pandas Dataframe to float

10,895

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
Share:
10,895
Braide
Author by

Braide

Updated on June 05, 2022

Comments

  • Braide
    Braide almost 2 years

    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?

    • Stephen Rauch
      Stephen Rauch over 6 years
      to_numeric does not work inplace, you need to assign its return value someplace