Pandas DataFrame.astype() Syntax

Syntax: DataFrame.astype(dtype, copy=True, errors=’raise’, **kwargs)

Parameters:

  • dtype : Use a numpy.dtype or Python type to cast 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 : Return a copy when copy=True (be very careful setting copy=False as changes to values then may propagate to other pandas objects).
  • errors : Control raising of exceptions on invalid data for provided dtype.
  • raise : allow exceptions to be raised
  • ignore : suppress exceptions. On error return original object
  • kwargs :keyword arguments to pass on to the constructor

Returns: casted : type of caller

For link to CSV file Used in Code, click here

Python | Pandas DataFrame.astype()

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.

DataFrame.astype() method is used to cast a pandas object to a specified dtype.astype() function also provides the capability to convert any suitable existing column to a categorical type.

DataFrame.astype() function comes in very handy when we want to compare a particular column data type to another data type. Not only that but we can also use a Python dictionary input to change more than one column type at once. The key label in the dictionary is corresponding to the column name and the values label in the dictionary corresponds to the new data types we want the columns to be of.

Similar Reads

Pandas DataFrame.astype() Syntax

Syntax: DataFrame.astype(dtype, copy=True, errors=’raise’, **kwargs) Parameters: dtype : Use a numpy.dtype or Python type to cast 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 : Return a copy when copy=True (be very careful setting copy=False as changes to values then may propagate to other pandas objects). errors : Control raising of exceptions on invalid data for provided dtype. raise : allow exceptions to be raised ignore : suppress exceptions. On error return original object kwargs :keyword arguments to pass on to the constructor Returns: casted : type of caller...

Python Pandas DataFrame.astype() Function Examples

Below are some examples of Pandas DataFrame.astype() Function:...