4

I wanted to convert all the 'object' type columns to another data type (float) in a dataframe without hard coding the column names. I was able to piece together some code from other answers that seems to work, but I feel like there's got to be a simpler way of doing this.

# Creating isolating columns of object data type
object_cols = df.loc[:, df.dtypes == 'O']

# Extracting column names with list comprehension
object_type_columns = [col for col in object_cols.columns]

# Converting column types of .astype in a for loop
for col in object_type_columns:
  df[col] = df[col].astype(float)

Let me know if there's any information I'm leaving out (I'm new at this). Thanks!

4 Answers 4

10

You can use select_dtypes to find the column names:

s = df.select_dtypes(include='object').columns
df[s] = df[s].astype("float")
Sign up to request clarification or add additional context in comments.

Comments

3

Try this, to convert the whole data frame all at once:

df = df.astype('float')

Comments

1

A method available from pandas version 2.0. is "convert_dtypes", which will find the best type match for the data. So as you posted in the question this will take care of objects converted to float or integer if that matches the column data.

df = df.convert_dtypes()

Comments

1

try this...

df.column_name.str.replace(r'\s+','').astype(float)

3 Comments

Maybe, but is has no explanation as to why it is a good solution.
I was going to ask, what exactly is the regex doing here?
@KristianCanler is it provides the answer for your question?

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.