Python Pandas - Changing some column types to categories

前端 未结 7 1479
孤独总比滥情好
孤独总比滥情好 2021-01-30 01:08

I have fed the following CSV file into iPython Notebook:

public = pd.read_csv(\"categories.csv\")
public

I\'ve also imported pandas as pd, nump

7条回答
  •  忘掉有多难
    2021-01-30 01:20

    Jupyter Notebook

    In my case, I had big Dataframe with many objects that I would like to convert it to category.

    Therefore, what I did is I selected the object columns and filled anything that is NA to missing and then saved it in the original Dataframe as in

    # Convert Object Columns to Categories
    obj_df =df.select_dtypes(include=['object']).copy()
    obj_df=obj_df.fillna('Missing')
    for col in obj_df:
        obj_df[col] = obj_df[col].astype('category')
    df[obj_df.columns]=obj_df[obj_df.columns]
    df.head()
    

    I hope this might be a helpful resource for later reference

提交回复
热议问题