How To Automatically Convert The DataTypes Of The DataFrame?


How To Automatically Convert The DataTypes Of The DataFrame?

Table Of Contents:

  1. Syntax To Convert DataTypes Of Data Frame.
  2. Examples Of Conversion Of DataType.

(1) Syntax:

DataFrame.convert_dtypes(infer_objects=True, convert_string=True, convert_integer=True, 
                         convert_boolean=True, convert_floating=True)

Description:

  • Convert columns to the best possible dtypes using dtypes supporting pd.NA

Parameters:

  1. infer_objects: bool, default True Whether object dtypes should be converted to the best possible types.
  2. convert_string: bool, default True- Whether object dtypes should be converted to StringDtype()
  3. convert_integer: bool, default True- Whether, if possible, conversion can be done to integer extension types.
  4. convert_boolean: bool, defaults True – Whether object dtypes should be converted to BooleanDtypes().
  5. convert_floating: bool, defaults True – Whether, if possible, conversion can be done to floating extension types. If convert_integer is also True, preference will be give to integer dtypes if the floats can be faithfully casted to integers.

(2) Examples Of Conversions :

Example-1

df1 = pd.DataFrame(
     {
         "a": pd.Series([1, 2, 3], dtype=np.dtype("int32")),
         "b": pd.Series(["x", "y", "z"], dtype=np.dtype("O")),
         "c": pd.Series([True, False, np.nan], dtype=np.dtype("O")),
         "d": pd.Series(["h", "i", np.nan], dtype=np.dtype("O")),
         "e": pd.Series([10, np.nan, 20], dtype=np.dtype("float")),
         "f": pd.Series([np.nan, 100.5, 200], dtype=np.dtype("float")),
    }
)
df1

Output:

df1.dtypes

Output:

a      int32
b     object
c     object
d     object
e    float64
f    float64
dtype: object
df2 = df1.convert_dtypes()
df2

Output:

df2.dtypes

Output:

a      Int32
b     string
c    boolean
d     string
e      Int64
f    Float64
dtype: object

Note:

  • Here you can see that the object types have been converted to the respective data types.

Leave a Reply

Your email address will not be published. Required fields are marked *