Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to Change column type in pandas?

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 columns contains values of the same type.
by

3 Answers

kshitijrana14
You can try this:
a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
df = pd.DataFrame(a, columns=['one', 'two', 'three'])
df
Out[16]:
one two three
0 a 1.2 4.2
1 b 70 0.03
2 x 5 0

df.dtypes
Out[17]:
one object
two object
three object

df[['two', 'three']] = df[['two', 'three']].astype(float)

df.dtypes
Out[19]:
one object
two float64
three float64
storm
ok
MounikaDasa
this below code will change datatype of column.

df[['col.name1', 'col.name2'...]] = df[['col.name1', 'col.name2'..]].astype('data_type')
in place of data type you can give your datatype .what do you want like str,float,int etc.

Login / Signup to Answer the Question.