How To Convert DataType Of The Columns In DataFrame?
Table Of Contents:
- Syntax To Convert DataType.
- Examples Of Converting DataType.
(1) Syntax:
DataFrame.astype(dtype, copy=True, errors='raise')
Description:
Cast a pandas object to a specified Data Type.
Parameters:
- dtype: Use a numpy.dtype or Python type to cast the entire pandas object to the same type. Alternatively, use {col: dtype, …}, where col is a column label and dtype is a numpy.dtype or Python type to cast one or more of the DataFrame’s columns to column-specific types.
- copy: bool, default True – Return a copy when
copy=True
(be very careful settingcopy=False
as changes to values then may propagate to other pandas objects). - errors{‘raise’, ‘ignore’}, default ‘raise’ –
Control raising of exceptions on invalid data for provided dtype.
raise
: allow exceptions to be raisedignore
: suppress exceptions. On error return the original object.
Returns:
casted: same type as caller
(2) Examples Of DataType Conversion :
Example-1
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
df.dtypes
Output:
col1 int64
col2 int64
dtype: object
df.astype('int32').dtypes
Output:
col1 int32
col2 int32
dtype: object
Example-2
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
df.dtypes
Output:
col1 int64
col2 int64
dtype: object
df.astype({'col1': 'int32'}).dtypes
Output:
col1 int32
col2 int64
dtype: object
Example-3
d = {'col1': [1, 2], 'col2': [3, 4]}
df1 = pd.DataFrame(data=d)
df1.dtypes
Output:
col1 int64
col2 int64
dtype: object
df2 = df1.astype('int64',copy=False)
df2['col1'][0] = 99
df1
Note:
- Here you can see that when you set copy=False, if you change the second DataFrame the First one is also changed.
- That means it has not been copied.