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.

Answer from Alex Riley on Stack Overflow
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
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › convert-a-dataframe-column-to-integer-in-pandas
Convert a Dataframe Column to Integer in Pandas - GeeksforGeeks
March 2, 2026 - This method is best when the data is clean, and you are sure that all values in the column can be successfully converted to integers without any errors. ... import pandas as pd # Creating a sample DataFrame data = {'Column1': ['1', '2', '3', '4']} df = pd.DataFrame(data) df['Column1'] = df['Column1'].astype(int) print(df) print(df['Column1'].dtype)
Discussions

How to convert a pandas column from strings to int
>>> df col 0 7 Average 1 6 Low Average 2 8 Good 3 11 Excellent 4 9 Better 5 5 Fair 6 10 Very Good 7 12 Luxury 8 4 Low 9 3 Poor 10 13 Mansion >>> df['col'] = df['col'].str.split(n=1, expand=True)[0].astype(int) >>> df col 0 7 1 6 2 8 3 11 4 9 5 5 6 10 7 12 8 4 9 3 10 13 More on reddit.com
🌐 r/learnpython
4
2
July 22, 2022
How to change datatype of an ID column from int to UUID for all my tables in the public schema
You can query information_schema.columns where table_schema = ‘public’. You can then dynamically pass these to your function or just generate a script and run that. More on reddit.com
🌐 r/Supabase
2
2
February 1, 2024
NaN to int
No, NaN is a floating point value. More on reddit.com
🌐 r/learnpython
16
4
February 1, 2023
Unable to convert a pandas object to a string in my DataFrame
object is just the dtype pandas uses for columns that contain values of type str (and many other Python types). The actual values themselves are still strings: import pandas as pd df = pd.DataFrame([["hello"], ["world"]], columns=["words"]) df.dtypes >>> words object dtype: object type(df.loc[0, "words"]) >>> Using .astype(str) does convert all values to string if they aren't already, but it doesn't change the column dtype by design. The only way around this is to use pandas's own string type via .astype("string"), but that's different from the str type, obviously. What exactly are the issues you are facing with the API? More on reddit.com
🌐 r/learnpython
6
3
December 10, 2021
🌐
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
If we want to convert a column to a sensible numeric data type (integer or float), we should use the to_numeric function. If we want Pandas to decide which data types to use for each column, we should use the convert_dtypes method.
🌐
Favtutor
favtutor.com › articles › pandas-convert-column-to-int
Convert the data type of Pandas column to int (with code)
December 29, 2023 - We can also use the astype() method to convert multiple columns to integer data type in a DataFrame. We can use the astype() method with a dictionary. The keys of the dictionary represent the column names, and the values represent the desired ...
🌐
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
🌐
LinkedIn
linkedin.com › pulse › change-data-type-columns-pandas-mohit-sharma
Change the data type of columns in Pandas
February 8, 2021 - If you wanted to try and force the conversion of both columns to an integer type, you could use df.astype(int) instead. Do follow or connect with me for articles on AWS and Machine Learning Topics. If you are interested in wanting particular topic comment below to let me know. Thank you. ... Thanks for your article. Very helpful. ... convert_dtypes is more powerful than infer_objets https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.convert_dtypes.html In some circumstances infer_objects doesn't convert to string and convert_dtypes does
Find elsewhere
🌐
Codegive
codegive.com › blog › pandas_change_column_type_to_int.php
Pandas Change Column Type to Int (2026): Master Data Conversions for Cleaner Analysis & Faster Insights!
To change a pandas column to an integer type, you can use the .astype(int) method for straightforward conversions or pd.to_numeric() with errors='coerce' for more robust handling of non-numeric values and NaNs.
🌐
GeeksforGeeks
geeksforgeeks.org › convert-the-data-type-of-pandas-column-to-int
Convert the data type of Pandas column to int - GeeksforGeeks
January 13, 2021 - Next we converted the column type using the astype() method. The final output is converted data types of column. ... import pandas as pd df = pd.DataFrame([["1", "2"], ["3", "4"]], columns = ["a", "b"]) df["a"] = df["a"].astype(str).astype(int) ...
🌐
Statology
statology.org › home › how to convert pandas dataframe columns to int
How to Convert Pandas DataFrame Columns to int
November 28, 2022 - #convert 'points' column to integer df['points'] = df['points'].astype(int) #view data types of each column df.dtypes player object points int64 assists object dtype: object · We can see that the ‘points’ column is now an integer, while all other columns remained unchanged. The following code shows how to convert multiple columns in a DataFrame to an integer: import pandas as pd #create DataFrame df = pd.DataFrame({'player': ['A', 'B', 'C', 'D', 'E'], 'points': ['25', '20', '14', '16', '27'], 'assists': ['5', '7', '7', '8', '11']}) #convert 'points' and 'assists' columns to integer df[['points', 'assists']] = df[['points', 'assists']].astype(int) #view data types for each column df.dtypes player object points int64 assists int64 dtype: object
🌐
w3resource
w3resource.com › python-exercises › pandas › python-pandas-data-frame-exercise-51.php
Pandas: Convert the datatype of a given column(floats to ints) - w3resource
September 6, 2025 - Write a Pandas program to change the datatype of a DataFrame column from object to int, handling conversion errors by filling with a default value. Write a Pandas program to convert a numeric column with decimal values to integer values using floor division, then compare the results with rounding.
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.astype.html
pandas.DataFrame.astype — pandas 3.0.3 documentation
Cast a numpy array to a specified type. ... Changed in version 2.0.0: Using astype to convert from timezone-naive dtype to timezone-aware dtype will raise an exception. Use Series.dt.tz_localize() instead. ... >>> d = {"col1": [1, 2], "col2": [3, 4]} >>> df = pd.DataFrame(data=d) >>> df.dtypes col1 int64 col2 int64 dtype: object ... >>> 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]
🌐
EDUCBA
educba.com › home › software development › software development tutorials › pandas tutorial › pandas convert column to int
Pandas Convert Column to Int | How to Convert Column to Int in Pandas?
April 1, 2023 - In this program also, first, import the pandas library and set the alias as pd. Then, define the columns of the table and print them. In order to identify the data type of objects, use “df.dtypes”. Here, it can be seen that the type of the second column is already int. Once this is completed, change the data type of the Rating column using df.Rating.astype(int).
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
GoLinuxCloud
golinuxcloud.com › home › databases › 7 ways to convert pandas dataframe column to int
7 ways to convert pandas DataFrame column to int | GoLinuxCloud
January 24, 2022 - Here we are going to use astype() method twice by specifying types. first method takes the old data type i.e float and second method take new data type i.e integer type ... # import the module import pandas # consider the food data ...
🌐
Arab Psychology
scales.arabpsychology.com › home › how to easily convert dataframe columns to integers in pandas
How To Easily Convert DataFrame Columns To Integers In Pandas
December 4, 2025 - To convert columns of a Pandas DataFrame to int, you can use the astype() method. This method takes as an argument the specific data type to which the column should be converted. For example, to convert a column currently stored as strings (object) ...
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.convert_dtypes.html
pandas.DataFrame.convert_dtypes — pandas 3.0.3 documentation
By using the options convert_string, convert_integer, convert_boolean and convert_floating, it is possible to turn off individual conversions to StringDtype, the integer extension types, BooleanDtype or floating extension types, respectively. For object-dtyped columns, if infer_objects is True, ...
🌐
Saturn Cloud
saturncloud.io › blog › pandas-tips-change-column-type
How to change column type in Pandas | Saturn Cloud Blog
October 4, 2023 - If you check the data types of the example above after converting all columns, you should see that you now have three int64 columns and one float64 column. One benefit of to_numeric() is built-in error handling, which comes in handy in cases with mixed dtypes. By default, this function raises an error if it encounters a value it can’t convert to numeric. You can change this behavior with the errors parameter: import pandas as pd data = pd.DataFrame({'a': '1 2 3'.split(), 'b': '10 20 chicken'.split()}) #default behavior - raises an error data['b'] = pd.to_numeric(data['b']) #ignore invalid values data['b'] = pd.to_numeric(data['b'], errors = 'ignore') #convert invalid values to NaN data['b'] = pd.to_numeric(data['b'], errors = 'coerce')
🌐
Statology
statology.org › home › how to change column type in pandas (with examples)
How to Change Column Type in Pandas (With Examples)
November 28, 2022 - The following code shows how to use the astype() function to convert all columns in the DataFrame to an integer data type:
🌐
Seaborn
deeplearningnerds.com › pandas-change-column-types-of-a-dataframe
Pandas - Change Column Types of a DataFrame
March 4, 2024 - # Convert string to integer df["users"] = df["users"].astype(int) # Convert string to boolean df["backend"] = df["backend"].map({"true": True, "false": False}) # Convert string to datetime df["date"] = pd.to_datetime(df["date"]) # Print schema df.dtypes · As you can see, the columns "users", "backend" and "date" now have the desired data types. Congratulations! Now you are one step closer to become an AI Expert. You have seen that it is very easy to change column types of a Pandas DataFrame.
🌐
Medium
medium.com › @filip.sekan › 3-ways-how-to-update-data-type-of-columns-in-pandas-97ddb5f32ae4
3 ways how to update data type of columns in Pandas | by Filip Sekan | Medium
February 3, 2023 - In this example, the data type of both the ‘age’ and ‘salary’ columns has been changed to ‘float64’. The pd.to_numeric() method is part of the Pandas library and is used to convert a column in a Pandas data frame from one data type ...