Home > Back-end >  Casting types of all columns starting with Pandas
Casting types of all columns starting with Pandas

Time:10-12

I have a df and several columns starting with 'comps' and I want to cast their types to float.

I tried

df = df.convert_dtypes() - Not Ok

df = df.columns.startswith('comps').astype(float) - Failed

Is there a fast way to do it?

Thanks

CodePudding user response:

Get all columns starting by comps and casting to floats:

d = dict.fromkeys(df.columns[df.columns.str.startswith('comps')], 'float')

d = dict.fromkeys(df.filter(regex='^comps').columns, 'float')
df = df.astype(d)
print (df)

Or:

m = df.columns.str.startswith('comps')
df.loc[:, m] = df.loc[:, m].astype(float)
print (df)

Or:

c = df.filter(regex='^comps').columns
df[c] = df[c].astype(float)
print (df)

Or:

df.update(df.filter(regex='^comps').astype(float))
print (df)

If casting to floats failed, is necessary use to_numeric:

m = df.columns.str.startswith('comps')
df.loc[:, m] = df.loc[:, m].apply(pd.to_numeric, errors='coerce')
print (df)

Or:

c = df.filter(regex='^comps').columns
df[c] = df[c].apply(pd.to_numeric, errors='coerce')
print (df)

Or:

df.update(df.filter(regex='^comps').apply(pd.to_numeric, errors='coerce'))
print (df)
  • Related