To modify the float output do this:

Copydf= pd.DataFrame(range(5), columns=['a'])
df.a = df.a.astype(float)
df

Out[33]:

          a
0 0.0000000
1 1.0000000
2 2.0000000
3 3.0000000
4 4.0000000

pd.options.display.float_format = '{:,.0f}'.format
df

Out[35]:

   a
0  0
1  1
2  2
3  3
4  4
Answer from EdChum on Stack Overflow
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.DataFrame.astype.html
pandas.DataFrame.astype โ€” pandas 3.0.3 documentation
>>> ser = pd.Series([1, 2], dtype="int32") >>> ser 0 1 1 2 dtype: int32 >>> ser.astype("int64") 0 1 1 2 dtype: int64 ... >>> from pandas.api.types import CategoricalDtype >>> cat_dtype = CategoricalDtype(categories=[2, 1], ordered=True) >>> ser.astype(cat_dtype) 0 1 1 2 dtype: category Categories (2, int64): [2 < 1]
๐ŸŒ
Medium
medium.com โ€บ @heyamit10 โ€บ understanding-pandas-astype-with-examples-f1b21ad17e69
Understanding pandas astype() with Examples | by Hey Amit | Medium
March 6, 2025 - This is where astype() truly shines because data isnโ€™t always clean, tidy, or in the format you expect. Youโ€™ll often need to tweak it, and thatโ€™s exactly what weโ€™ll do here. ... Imagine youโ€™ve got a DataFrame with mixed data types โ€” some numbers stored as integers, others as strings. Instead of converting each column one by one (which is tedious), you can handle them all at once using a dictionary. ... import pandas as pd # Sample DataFrame with mixed data types data = {'A': [1, 2, 3], 'B': ['4', '5', '6']} df = pd.DataFrame(data) # Convert column A to float and B to integer df = df.astype({'A': 'float', 'B': 'int'}) # Check the new data types print(df.dtypes)
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-pandas-dataframe-astype
Pandas DataFrame.astype()-Python - GeeksforGeeks
June 26, 2025 - Explanation: astype() method is used with a dictionary to convert 'A' to integer and 'B' to float. Both columns are now in numeric form, suitable for calculations. Example 3: In this, we try to convert column 'A' to integer, but due to a non-numeric ...
๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ python โ€บ third-party โ€บ pandas โ€บ DataFrame โ€บ astype
Python Pandas DataFrame astype() - Change Data Type | Vultr Docs
December 24, 2024 - This code converts the col2 from string type to integer type. The operation is performed in-place, directly modifying the data frame. Consider a DataFrame with several columns of different types. Use astype() to alter multiple columns at once.
๐ŸŒ
iO Flood
ioflood.com โ€บ blog โ€บ pandas-astype
Pandas astype() Function | Data Type Conversion Guide
June 6, 2024 - We then used the astype() function to convert the data type of the โ€˜Aโ€™ column to integers. The output shows the DataFrame with the โ€˜Aโ€™ column now containing integers instead of strings. Keep reading for a more detailed explanation and advanced usage scenarios of the pandas astype() function.
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python โ€บ pandas
pandas: How to use astype() to cast dtype of DataFrame | note.nkmk.me
August 9, 2023 - source: pandas_implicit_type_conversion.py ยท For arithmetic operations like +, -, *, //, and **, operations involving only integers return int, while those involving at least one floating-point number return float. This is equivalent to the implicit type conversion of the NumPy array ndarray. NumPy: Cast ndarray to a specific dtype with astype() print(df_mix * 1) # col_int col_float # A 0 0.0 # B 1 0.1 # C 2 0.2 print((df_mix * 1).dtypes) # col_int int64 # col_float float64 # dtype: object print(df_mix * 1.0) # col_int col_float # A 0.0 0.0 # B 1.0 0.1 # C 2.0 0.2 print((df_mix * 1.0).dtypes) # col_int float64 # col_float float64 # dtype: object ยท
๐ŸŒ
Favtutor
favtutor.com โ€บ articles โ€บ pandas-convert-column-to-int
Convert the data type of Pandas column to int (with code)
December 29, 2023 - Let us look at an example of how to use the astpye() function to change a column into an integer data type: import pandas as pd # Creating a DataFrame data = {'Roll Number': [46.0, 35.0, 42.0], 'Age': [25.1 , 30.2 , 22.2]} df = pd.DataFrame(data) # Display the original DataFrame print('Original DataFrame:\n', df) # Using the astype() method df = df.astype('int') # Display the new DataFrame print('New DataFrame:\n', df)
Find elsewhere
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ pandas โ€บ pandas convert column to int in dataframe
Pandas Convert Column to Int in DataFrame - Spark By {Examples}
June 26, 2025 - How to convert the Pandas column to int in DataFrame? You can use DataFrame.astype(int) or DataFrame.apply() method to convert a column to int
๐ŸŒ
Medium
medium.com โ€บ @amit25173 โ€บ pandas-float-to-int-a-practical-guide-a288ab2fe3d9
Pandas Float to Int: A Practical Guide | by Amit Yadav | Medium
March 6, 2025 - Using .astype("int64") โ€“ Explicit Data Type Conversion ยท Pandas stores integer columns in various formats (int8, int16, int32, int64).
๐ŸŒ
Pandasdataframe
pandasdataframe.com โ€บ pandas-astype-int.html
Pandas astype int-Pandas Dataframe
The astype(int) method converts the float values in column โ€˜Aโ€™ to integers. The print(df) statement outputs the modified DataFrame, showing the converted integer values. When converting data types, it is crucial to handle missing values appropriately. Pandas uses NaN (Not a Number) to represent missing values, which are float by default.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ pandas โ€บ ref_df_astype.asp
Pandas DataFrame astype() Method
The astype() method returns a new DataFrame where the data types has been changed to the specified type. You can cast the entire DataFrame to one specific data type, or you can use a Python Dictionary to specify a data type for each column, ...
๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ python โ€บ change a column type in a dataframe in python pandas
Change a column type in a DataFrame in Python Pandas | Sentry
import pandas as pd # Create and print DataFrame df = pd.DataFrame({ 'A': ['1', '2', '3'], 'B': ['4', '5', '6'], 'C': ['7', '8', '9'] }) print(df) # Print data types of each column in DataFrame print("\n") print(df.dtypes) # Change column A's values to floats df['A'] = df['A'].astype(float) # Change column B and C's values to integers df = df.astype({'B': int, 'C': int}) print("\nConverted:\n") # Print altered DataFrame print(df) # Print data types of each column in DataFrame print("\n") print(df.dtypes)
๐ŸŒ
Pandas
pandas.pydata.org โ€บ pandas-docs โ€บ stable โ€บ reference โ€บ api โ€บ pandas.DataFrame.astype.html
pandas.DataFrame.astype โ€” pandas 3.0.1 documentation
>>> ser = pd.Series([1, 2], dtype="int32") >>> ser 0 1 1 2 dtype: int32 >>> ser.astype("int64") 0 1 1 2 dtype: int64 ... >>> from pandas.api.types import CategoricalDtype >>> cat_dtype = CategoricalDtype(categories=[2, 1], ordered=True) >>> ser.astype(cat_dtype) 0 1 1 2 dtype: category Categories (2, int64): [2 < 1]
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.Index.astype.html
pandas.Index.astype โ€” pandas 3.0.3 documentation - PyData |
Index.astype(dtype, copy=True)[source]# Create an Index with values cast to dtypes. The class of a new Index is determined by dtype. When conversion is impossible, a TypeError exception is raised. Parameters: dtypenumpy dtype or pandas type ยท Note that any signed integer dtype is treated as 'int64', and any unsigned integer dtype is treated as 'uint64', regardless of the size.
๐ŸŒ
DEV Community
dev.to โ€บ atifwattoo โ€บ what-is-astype-function-in-python-4bg5
What is astype() function in Python - DEV Community
January 8, 2025 - The astype() function is used to cast the data type of a pandas object (like a Series or DataFrame) or a NumPy array into another type.
Top answer
1 of 16
2639

You have four main options for converting types in pandas:

  1. to_numeric() - provides functionality to safely convert non-numeric types (e.g. strings) to a suitable numeric type. (See also to_datetime() and to_timedelta().)

  2. astype() - convert (almost) any type to (almost) any other type (even if it's not necessarily sensible to do so). Also allows you to convert to categorial types (very useful).

  3. infer_objects() - a utility method to convert object columns holding Python objects to a pandas type if possible.

  4. convert_dtypes() - convert DataFrame columns to the "best possible" dtype that supports pd.NA (pandas' object to indicate a missing value).

Read on for more detailed explanations and usage of each of these methods.


1. to_numeric()

The best way to convert one or more columns of a DataFrame to numeric values is to use pandas.to_numeric().

This function will try to change non-numeric objects (such as strings) into integers or floating-point numbers as appropriate.

Basic usage

The input to to_numeric() is a Series or a single column of a DataFrame.

>>> s = pd.Series(["8", 6, "7.5", 3, "0.9"]) # mixed string and numeric values
>>> s
0      8
1      6
2    7.5
3      3
4    0.9
dtype: object

>>> pd.to_numeric(s) # convert everything to float values
0    8.0
1    6.0
2    7.5
3    3.0
4    0.9
dtype: float64

As you can see, a new Series is returned. Remember to assign this output to a variable or column name to continue using it:

# convert Series
my_series = pd.to_numeric(my_series)

# convert column "a" of a DataFrame
df["a"] = pd.to_numeric(df["a"])

You can also use it to convert multiple columns of a DataFrame via the apply() method:

# convert all columns of DataFrame
df = df.apply(pd.to_numeric) # convert all columns of DataFrame

# convert just columns "a" and "b"
df[["a", "b"]] = df[["a", "b"]].apply(pd.to_numeric)

As long as your values can all be converted, that's probably all you need.

Error handling

But what if some values can't be converted to a numeric type?

to_numeric() also takes an errors keyword argument that allows you to force non-numeric values to be NaN, or simply ignore columns containing these values.

Here's an example using a Series of strings s which has the object dtype:

>>> s = pd.Series(['1', '2', '4.7', 'pandas', '10'])
>>> s
0         1
1         2
2       4.7
3    pandas
4        10
dtype: object

The default behaviour is to raise if it can't convert a value. In this case, it can't cope with the string 'pandas':

>>> pd.to_numeric(s) # or pd.to_numeric(s, errors='raise')
ValueError: Unable to parse string

Rather than fail, we might want 'pandas' to be considered a missing/bad numeric value. We can coerce invalid values to NaN as follows using the errors keyword argument:

>>> pd.to_numeric(s, errors='coerce')
0     1.0
1     2.0
2     4.7
3     NaN
4    10.0
dtype: float64

The third option for errors is just to ignore the operation if an invalid value is encountered:

>>> pd.to_numeric(s, errors='ignore')
# the original Series is returned untouched

This last option is particularly useful for converting your entire DataFrame, but don't know which of our columns can be converted reliably to a numeric type. In that case, just write:

df.apply(pd.to_numeric, errors='ignore')

The function will be applied to each column of the DataFrame. Columns that can be converted to a numeric type will be converted, while columns that cannot (e.g. they contain non-digit strings or dates) will be left alone.

Downcasting

By default, conversion with to_numeric() will give you either an int64 or float64 dtype (or whatever integer width is native to your platform).

That's usually what you want, but what if you wanted to save some memory and use a more compact dtype, like float32, or int8?

to_numeric() gives you the option to downcast to either 'integer', 'signed', 'unsigned', 'float'. Here's an example for a simple series s of integer type:

>>> s = pd.Series([1, 2, -7])
>>> s
0    1
1    2
2   -7
dtype: int64

Downcasting to 'integer' uses the smallest possible integer that can hold the values:

>>> pd.to_numeric(s, downcast='integer')
0    1
1    2
2   -7
dtype: int8

Downcasting to 'float' similarly picks a smaller than normal floating type:

>>> pd.to_numeric(s, downcast='float')
0    1.0
1    2.0
2   -7.0
dtype: float32

2. astype()

The astype() method enables you to be explicit about the dtype you want your DataFrame or Series to have. It's very versatile in that you can try and go from one type to any other.

Basic usage

Just pick a type: you can use a NumPy dtype (e.g. np.int16), some Python types (e.g. bool), or pandas-specific types (like the categorical dtype).

Call the method on the object you want to convert and astype() will try and convert it for you:

# convert all DataFrame columns to the int64 dtype
df = df.astype(int)

# convert column "a" to int64 dtype and "b" to complex type
df = df.astype({"a": int, "b": complex})

# convert Series to float16 type
s = s.astype(np.float16)

# convert Series to Python strings
s = s.astype(str)

# convert Series to categorical type - see docs for more details
s = s.astype('category')

Notice I said "try" - if astype() does not know how to convert a value in the Series or DataFrame, it will raise an error. For example, if you have a NaN or inf value you'll get an error trying to convert it to an integer.

As of pandas 0.20.0, this error can be suppressed by passing errors='ignore'. Your original object will be returned untouched.

Be careful

astype() is powerful, but it will sometimes convert values "incorrectly". For example:

>>> s = pd.Series([1, 2, -7])
>>> s
0    1
1    2
2   -7
dtype: int64

These are small integers, so how about converting to an unsigned 8-bit type to save memory?

>>> s.astype(np.uint8)
0      1
1      2
2    249
dtype: uint8

The conversion worked, but the -7 was wrapped round to become 249 (i.e. 28 - 7)!

Trying to downcast using pd.to_numeric(s, downcast='unsigned') instead could help prevent this error.


3. infer_objects()

Version 0.21.0 of pandas introduced the method infer_objects() for converting columns of a DataFrame that have an object datatype to a more specific type (soft conversions).

For example, here's a DataFrame with two columns of object type. One holds actual integers and the other holds strings representing integers:

>>> df = pd.DataFrame({'a': [7, 1, 5], 'b': ['3','2','1']}, dtype='object')
>>> df.dtypes
a    object
b    object
dtype: object

Using infer_objects(), you can change the type of column 'a' to int64:

>>> df = df.infer_objects()
>>> df.dtypes
a     int64
b    object
dtype: object

Column 'b' has been left alone since its values were strings, not integers. If you wanted to force both columns to an integer type, you could use df.astype(int) instead.


4. convert_dtypes()

Version 1.0 and above includes a method convert_dtypes() to convert Series and DataFrame columns to the best possible dtype that supports the pd.NA missing value.

Here "best possible" means the type most suited to hold the values. For example, this a pandas integer type, if all of the values are integers (or missing values): an object column of Python integer objects are converted to Int64, a column of NumPy int32 values, will become the pandas dtype Int32.

With our object DataFrame df, we get the following result:

>>> df.convert_dtypes().dtypes                                             
a     Int64
b    string
dtype: object

Since column 'a' held integer values, it was converted to the Int64 type (which is capable of holding missing values, unlike int64).

Column 'b' contained string objects, so was changed to pandas' string dtype.

By default, this method will infer the type from object values in each column. We can change this by passing infer_objects=False:

>>> df.convert_dtypes(infer_objects=False).dtypes                          
a    object
b    string
dtype: object

Now column 'a' remained an object column: pandas knows it can be described as an 'integer' column (internally it ran infer_dtype) but didn't infer exactly what dtype of integer it should have so did not convert it. Column 'b' was again converted to 'string' dtype as it was recognised as holding 'string' values.

2 of 16
553

Use 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
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ pandas โ€บ methods โ€บ astype
Pandas astype()
import pandas as pd # sample DataFrame data = {'A': ['1', '2', '3'], 'B': ['4', '5', '6']} df = pd.DataFrame(data) # convert data types of columns A and B df = df.astype({'A': int, 'B': float}) print(df) Output ยท A B 0 1 4.0 1 2 5.0 2 3 6.0 ยท
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ pandas โ€บ pandas dataframe.astype() โ€“ examples
Pandas DataFrame.astype() - Examples - Spark By {Examples}
July 7, 2025 - DataFrame.astype() function is used to cast a column data type (dtype) in pandas object, it supports String, flat, date, int, datetime any many other