Convert columns of the DataFrame to category dtype. .. warning:: This method eagerly computes the categories of the chosen columns. Parameters ---------- columns : list, optional A list of column names to convert to categoricals. By default any
(self, columns=None, index=None, split_every=None, **kwargs)
| 3785 | return self._comparison_op(expr.EQFrame, other, level, axis) |
| 3786 | |
| 3787 | def categorize(self, columns=None, index=None, split_every=None, **kwargs): |
| 3788 | """Convert columns of the DataFrame to category dtype. |
| 3789 | |
| 3790 | .. warning:: This method eagerly computes the categories of the chosen columns. |
| 3791 | |
| 3792 | Parameters |
| 3793 | ---------- |
| 3794 | columns : list, optional |
| 3795 | A list of column names to convert to categoricals. By default any |
| 3796 | column with an object dtype is converted to a categorical, and any |
| 3797 | unknown categoricals are made known. |
| 3798 | index : bool, optional |
| 3799 | Whether to categorize the index. By default, object indices are |
| 3800 | converted to categorical, and unknown categorical indices are made |
| 3801 | known. Set True to always categorize the index, False to never. |
| 3802 | split_every : int, optional |
| 3803 | Group partitions into groups of this size while performing a |
| 3804 | tree-reduction. If set to False, no tree-reduction will be used. |
| 3805 | kwargs |
| 3806 | Keyword arguments are passed on to compute. |
| 3807 | """ |
| 3808 | df = self |
| 3809 | meta = df._meta |
| 3810 | if columns is None: |
| 3811 | columns = list(meta.select_dtypes(["object", "string", "category"]).columns) |
| 3812 | elif is_scalar(columns): |
| 3813 | columns = [columns] |
| 3814 | |
| 3815 | # Filter out known categorical columns |
| 3816 | columns = [ |
| 3817 | c |
| 3818 | for c in columns |
| 3819 | if not (is_categorical_dtype(meta[c]) and has_known_categories(meta[c])) |
| 3820 | ] |
| 3821 | |
| 3822 | if index is not False: |
| 3823 | if is_categorical_dtype(meta.index): |
| 3824 | index = not has_known_categories(meta.index) |
| 3825 | elif index is None: |
| 3826 | index = str(meta.index.dtype) in ("object", "string") |
| 3827 | |
| 3828 | # Nothing to do |
| 3829 | if not len(columns) and index is False: |
| 3830 | return df |
| 3831 | |
| 3832 | from dask.dataframe.dask_expr._collection import new_collection |
| 3833 | |
| 3834 | # Eagerly compute the categories |
| 3835 | categories, index = new_collection( |
| 3836 | GetCategories(self, columns=columns, index=index, split_every=split_every) |
| 3837 | ).compute() |
| 3838 | |
| 3839 | # Some operations like get_dummies() rely on the order of categories |
| 3840 | categories = {k: v.sort_values() for k, v in categories.items()} |
| 3841 | |
| 3842 | # Categorize each partition |
| 3843 | return new_collection(Categorize(self, categories, index)) |
| 3844 |