How to Change the Data Type of a Column in Pandas
We will look at methods for changing the data type of columns in a Pandas Dataframe, as well as options like to_numaric
, , as_type
and infer_objects
. We will also discuss how to to_numaric
use downcasting
the option in .
to_numeric
Method to convert columns to numeric values in Pandas
to_numeric()
is the best way to convert one or more columns of a dataFrame to numeric values. It also attempts to change non-numeric objects (such as strings) to integers or floating point numbers as appropriate. to_numeric()
The input can be a column of Series
or DataFrame
. If some values cannot be converted to a numeric type, to_numeric()
allows us to coerce non-numeric values to NaN.
Code example:
# python 3.x
import pandas as pd
s = pd.Series(["12", "12", "4.7", "asad", "3.0"])
print(s)
print("------------------------------")
print(pd.to_numeric(s, errors="coerce"))
Output:
0 12
1 12
2 4.7
3 asad
4 3.0
dtype: object0 12.0
1 12.0
2 4.7
3 NaN
4 3.0
dtype: float64
By default, to_numeric()
we are given int64
a float64
dtype of . We can use an option to convert to integer
, signed
, unsigned
or float
:
# python 3.x
import pandas as pd
s = pd.Series([-3, 1, -5])
print(s)
print(pd.to_numeric(s, downcast="integer"))
Output:
0 -3
1 1
2 -5
dtype: int64
0 -3
1 1
2 -5
dtype: int8
astype()
Method to convert one type to any other data type
astype() method allows us to be explicit about the dtype we want to convert. By astype()
passing the argument inside the method, we can go from one data type to another.
Consider the following code:
# python 3.x
import pandas as pd
c = [["x", "1.23", "14.2"], ["y", "20", "0.11"], ["z", "3", "10"]]
df = pd.DataFrame(c, columns=["first", "second", "third"])
print(df)
df[["second", "third"]] = df[["second", "third"]].astype(float)
print("Converting..................")
print("............................")
print(df)
Output:
first second third
0 x 1.23 14.2
1 y 20 0.11
2 z 3 10
Converting..................
............................
first second third
0 x 1.23 14.20
1 y 20.00 0.11
2 z 3.00 10.00
infer_objects()
Method to convert column data type to a more specific type
infer_objects()
The method introduced in Pandas version 0.21.0 is used to dataFrame
convert a column of to a more specific data type (soft conversion).
Consider the following code:
# python 3.x
import pandas as pd
df = pd.DataFrame({"a": [3, 12, 5], "b": [3.0, 2.6, 1.1]}, dtype="object")
print(df.dtypes)
df = df.infer_objects()
print("Infering..................")
print("............................")
print(df.dtypes)
Output:
a object
b object
dtype: object
Infering..................
............................
a int64
b float64
dtype: object
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Finding the installed version of Pandas
Publish Date:2025/04/12 Views:190 Category:Python
-
Pandas is one of the commonly used Python libraries for data analysis, and Pandas versions need to be updated regularly. Therefore, other Pandas requirements are incompatible. Let's look at ways to determine the Pandas version and dependenc
KeyError in Pandas
Publish Date:2025/04/12 Views:81 Category:Python
-
This tutorial explores the concept of KeyError in Pandas. What is Pandas KeyError? While working with Pandas, analysts may encounter multiple errors thrown by the code interpreter. These errors are wide ranging and can help us better invest
Grouping and Sorting in Pandas
Publish Date:2025/04/12 Views:90 Category:Python
-
This tutorial explored the concept of grouping data in a DataFrame and sorting it in Pandas. Grouping and Sorting DataFrame in Pandas As we know, Pandas is an advanced data analysis tool or package extension in Python. Most of the companies
Plotting Line Graph with Data Points in Pandas
Publish Date:2025/04/12 Views:65 Category:Python
-
Pandas is an open source data analysis library in Python. It provides many built-in methods to perform operations on numerical data. Data visualization is very popular nowadays and is used to quickly analyze data visually. We can visualize
Converting Timedelta to Int in Pandas
Publish Date:2025/04/12 Views:123 Category:Python
-
This tutorial will discuss converting a to a using dt the attribute in Pandas . timedelta int Use the Pandas dt attribute to timedelta convert int To timedelta convert to an integer value, we can use the property pandas of the library dt .
Pandas fill NaN values
Publish Date:2025/04/12 Views:93 Category:Python
-
This tutorial explains how we can use DataFrame.fillna() the method to fill NaN values with specified values. We will use the following DataFrame in this article. import numpy as np import pandas as pd roll_no = [ 501 , 502 , 503 , 50
Pandas Convert String to Number
Publish Date:2025/04/12 Views:147 Category:Python
-
This tutorial explains how to pandas.to_numeric() convert string values of a Pandas DataFrame into numeric type using the method. import pandas as pd items_df = pd . DataFrame( { "Id" : [ 302 , 504 , 708 , 103 , 343 , 565 ], "Name" :
Get the first row of Dataframe Pandas
Publish Date:2025/04/12 Views:78 Category:Python
-
This tutorial explains how to use the get_first_row pandas.DataFrame.iloc attribute and pandas.DataFrame.head() get_first_row method from a Pandas DataFrame. We will use the following DataFrame in the following example to explain how to get
Pandas Drop Duplicate Rows in DataFrame
Publish Date:2025/04/12 Views:75 Category:Python
-
This tutorial explains how to DataFrame.drop_duplicates() remove all duplicate rows from a Pandas DataFrame using the remove_by method. DataFrame.drop_duplicates() grammar DataFrame . drop_duplicates(subset = None , keep = "first" , inplace