Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting pandas Dataframe to float

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?

like image 279
Braide Avatar asked Oct 15 '25 20:10

Braide


1 Answers

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
like image 155
FatihAkici Avatar answered Oct 18 '25 14:10

FatihAkici



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!