Python Pandas - Changing some column types to categories

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

    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  e
    
    df.dtypes
    >> a    object
    >> b    object
    >> dtype: object
    
    df[df.columns] = df[df.columns].astype('category')
    df.dtypes
    >> a    category
    >> b    category
    >> dtype: object
    

提交回复
热议问题