Get list of pandas dataframe columns based on data type
Quickly grab columns by data type in a pandas DataFrame using select_dtypes
. For instance, fetch all float
columns as follows:
Combine different types like int
and bool
in a similar fashion:
Another reliable way to filter is through dtypes
:
To add a layer of customization and cater to dynamic type selection, you can wrap this in a function:
On-demand selection with user-friendly functions
Flexible type selection with a function
Advancing from ad-hoc filters, consider capturing the selection process in a utility function for ease of use and better reusability:
Operating directly with dtypes
For more control, you can even operate with the dtypes
property directly:
Leveraging the power of masks
To manipulate columns of specific types, a boolean mask can come in handy:
Use this mask to pull off type-specific operations:
Advanced techniques with dtype groups & conversions
Grouping by dtypes
We can use the groupby
feature with dtypes
for a grouped view of data types:
This results in a neatly packed dictionary housing a group-wise distribution of column lists.
Converting column data types
Sometimes, it's just simpler to convert column types:
Was this article helpful?