How To Automatically Convert The DataTypes Of The DataFrame?
Table Of Contents:
- Syntax To Convert DataTypes Of Data Frame.
- 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:
- infer_objects: bool, default True – Whether object dtypes should be converted to the best possible types.
- convert_string: bool, default True- Whether object dtypes should be converted to
StringDtype()
- convert_integer: bool, default True- Whether, if possible, conversion can be done to integer extension types.
- convert_boolean: bool, defaults True – Whether object dtypes should be converted to
BooleanDtypes()
. - 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.