Python Pandas - Changing some column types to categories

前端 未结 7 1291
孤独总比滥情好
孤独总比滥情好 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:15

    You can use the pandas.DataFrame.apply method along with a lambda expression to solve this. In your example you could use

    df[['parks', 'playgrounds', 'sports']].apply(lambda x: x.astype('category'))
    

    I don't know of a way to execute this inplace, so typically I'll end up with something like this:

    df[df.select_dtypes(['object']).columns] = df.select_dtypes(['object']).apply(lambda x: x.astype('category'))
    

    Obviously you can replace .select_dtypes with explicit column names if you don't want to select all of a certain datatype (although in your example it seems like you wanted all object types).

提交回复
热议问题