Python | Pandas dataframe.infer_objects ()

Python Methods and Functions

The Pandas dataframe.infer_objects() function tries to determine the best data type for the input object column. This function tries to gently convert object columns while leaving non-object and irreversible columns intact. Inference rules are the same as for normal Series / DataFrame building.

Syntax: DataFrame.infer_objects ()
Returns: converted: same type as input object

Example # 1: Use infer_objects () to determine the best data type.

Output:

Let`s see the dtype (data type) of each column in the data frame.

# import pandas as pd

import pandas as pd

  
# Create a data frame

df = pd.DataFrame ({ "A" : [ "sofia" , 5 , 8 , 11 , 100 ],

"B" : [ 2 , 8 , 77 , 4 , 11 ],

"C" : [ "amy" , 11 , 4 , 6 , 9 ]})

  
# Print the data frame

df

# print basic information
df.info ()

As we can see in the output, the first and third columns are of type object . whereas the second column is of type int64 . Now slice the dataframe and create a new dataframe from it.

# cut from 1st row to end

df_new = df [ 1 :]

 
# Let`s print a new data frame
df_new

 
# Now let`s print the data type of the columns
df_new.info ()

Output:

As we see in the output, the columns" A " and "C" are of object type even if they contain an integer value. So let`s try infer_objects () .

# using infer_objects () function.

df_new = df_new.infer_objects ()

 
# Print dtype after function is applied
df_new. info ()

Output:

Now if we look at the d type of each column, we can see that columns "A" and " C "is now int64 of type int64 .

Example # 2: Use infer_objects () to determine the best data type for the object.

# import pandas as pd

import pandas as pd

 
# Create data frame

df = pd.DataFrame ({ "A" : [ "sofia" , 5 , 8 , 11 , 100 ], 

  "B" : [ 2 + 2j , 8 , 77 , 4 , 11 ],

"C" : [ "amy" , 11 , 4 , 6 , 9 ]})

 
# Print the data frame
df

Let`s see the dtype (data type) of each column in the data frame.

# print basic information
df.info ()

As we can see in the output, the first and third columns are of type object . whereas the second column is complex128 of type complex128 . Now slice the dataframe and create a new dataframe from it.

# cut from 1st row to end

df_new = df [ 1 :]

 
# Let`s print a new data frame
df_new

 
# Now let`s print the data type of the columns
df_new.info ()


As we can see in the output, columns "A" and "C" are of object type, even if they contain an integer value. The situation is similar with the column "B". So let`s try infer_objects () .

# using infer_objects () function.

df_new = df_new.infer_objects ()

 
# Print dtype after function is applied
df_new. info ()

Output:

Please note that the d type for column "B" has not changed.  infer_objects () tries to perform a soft conversion, leaving non-object and irreversible columns intact.





Get Solution for free from DataCamp guru