Python Pandas - Changing some column types to categories Python Pandas - Changing some column types to categories python python

Python Pandas - Changing some column types to categories


Sometimes, you just have to use a for-loop:

for col in ['parks', 'playgrounds', 'sports', 'roading']:    public[col] = public[col].astype('category')


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).


No need for loops, Pandas can do it directly now, just pass a list of columns you want to convert and Pandas will convert them all.

cols = ['parks', 'playgrounds', 'sports', 'roading']public[cols] = public[cols].astype('category')

df = pd.DataFrame({'a': ['a', 'b', 'c'], 'b': ['c', 'd', 'e']})>>     a  b>>  0  a  c>>  1  b  d>>  2  c  edf.dtypes>> a    object>> b    object>> dtype: objectdf[df.columns] = df[df.columns].astype('category')df.dtypes>> a    category>> b    category>> dtype: object