Change data type of columns in Pandas

Python

I want to convert a table, represented as a list of lists, into a Pandas DataFrame. As an extremely simplified example:

a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']] 

df = pd.DataFrame(a)

What is the best way to convert the columns to the appropriate types, in this case, columns 2 and 3 into floats? Is there a way to specify the types while converting to DataFrame? Or is it better to create the DataFrame first and then loop through the columns to change the type for each column? Ideally, I would like to do this in a dynamic way because there can be hundreds of columns and I don't want to specify exactly which columns are of which type. All I can guarantee is that each column contains values of the same type.


If you want to unleash your potential in this competitive field, please visit the Python course page for more information, where you can find the Python tutorials and Python frequently asked interview questions and answers as well.

1
Answers

Replies


Pandas provide four options to convert types.


to_numeric() - converts a non-numeric type to a numeric type.


astype() - converts any type to any type.


infer_objects() - converts object columns to a pandas type.


convert_dtypes() - converts data frame columns to dtype (pandas object).


 

 
 

This topic has been locked/unapproved. No replies allowed

Login to participate in this discussion.

Leave a reply

Before proceeding, please check your email for a verification link. If you did not receive the email, click here to request another.
WhatsApp
To Top