Signup/Sign In

Pandas DataFrame infer_objects() Method

In this tutorial, we will learn the Python pandas DataFrame.infer_objects() method. It attempts to infer better dtypes for object columns. This method tries to the soft conversion of object-dtyped columns, leaving non-object and unconvertible columns unchanged. The inference rules are the same as during normal Series or the DataFrame construction.

The below shows the syntax of the DataFrame.infer_objects() method.

Syntax

DataFrame.infer_objects()

Example 1: The DataFrame.infer_objects() Method

Let's take a DataFrame and check the dtype of the DataFrame. Convert the dtypes of columns of the DataFrame using the DataFrame.infer_objects() method.

#importing pandas as pd
import pandas as pd
df = pd.DataFrame({'a': ["abc",7, 1, 5], 'b': ["xyz",'3','2','1']})
print("----DataTypes of the DataFrame is-----")
print(df.dtypes)
df_1 = df.iloc[1:]
print("----DataTypes of the new DataFrame is-----")
print(df_1.dtypes)
print("----After conversion DataTypes of the DataFrame is----")
df_2=df_1.infer_objects()
print(df_2.dtypes)


----DataTypes of the DataFrame is-----
a object
b object
dtype: object
----DataTypes of the new DataFrame is-----
a object
b object
dtype: object
----After conversion DataTypes of the DataFrame is----
a int64
b object
dtype: object

Example 2: The DataFrame.infer_objects() Method

This is another example to convert dtype of columns by using the DataFrame.infer_objects() method.

#importing pandas as pd
import pandas as pd
df = pd.DataFrame({'a': [7, 1, 5], 'b': ['3','2','1']}, dtype='object')
print("----DataTypes of the DataFrame is-----")
print(df.dtypes)
print("----After conversion DataTypes of the DataFrame is----")
df_1=df.infer_objects()
print(df_1.dtypes)


----DataTypes of the DataFrame is-----
a object
b object
dtype: object
----After conversion DataTypes of the DataFrame is----
a int64
b object
dtype: object

Conclusion

In this tutorial, we learned the python pandas DataFrame.infer_objects() method. We convert the type of columns of the DataFrame using the DataFrame.infer_objects() method.



About the author:
I like writing about Python, and frameworks like Pandas, Numpy, Scikit, etc. I am still learning Python. I like sharing what I learn with others through my content.