Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert pandas columns to double in for loop?

Tags:

python

pandas

I have a pandas dataframe called df10.

cols10 = list(df10.columns)

I want to change the data type to double where the column name starts with "m_"

for param in cols10:
    if param.startswith("m_"):
        df10[[param]] = df10[[param]].apply(pd.to_double)

However, I'm getting this error:

AttributeError: 'module' object has no attribute 'to_double'
like image 918
Cody Avatar asked Dec 19 '22 01:12

Cody


2 Answers

the function to_double doesn't exist in pandas. pandas datatypes are essentially numpy data types

i'm assuming you mean float64 by double

you can either let numpy decide the precision for you

for col in cols10:
    if col.startswith('m_'):
        df[col] = df[col].astype(float)

or specify the precision yourself

for col in cols10:
    if col.startswith('m_'):
        df[col] = df[col].astype(np.float64) # or np.float32 or np.float16
like image 61
Haleemur Ali Avatar answered Dec 27 '22 00:12

Haleemur Ali


You can do this without loop,

reqd_cols = df10.columns[df10.columns.str.startswith('m_')]
df10[reqd_cols] = df10[reqd_cols].astype('float64')
like image 20
Vaishali Avatar answered Dec 27 '22 02:12

Vaishali