Pandas将所有对象列强制转换为类别

Geo*_*ler 3 python casting pandas categorical-data

我想要ha优雅的功能将pandas数据框中的所有对象列转换为类别

df[x] = df[x].astype("category")执行类型转换 df.select_dtypes(include=['object'])将子选择所有类别列.但是,这会导致其他列丢失/需要手动合并.有没有"只是在适当的地方工作"或不需要手动演员的解决方案?

编辑

我正在寻找类似http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.convert_objects.html的内容,以转换为分类数据

piR*_*red 7

使用applypd.Series.astypedtype='category'

考虑一下 pd.DataFrame df

df = pd.DataFrame(dict(
        A=[1, 2, 3, 4],
        B=list('abcd'),
        C=[2, 3, 4, 5],
        D=list('defg')
    ))
df
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 4 columns):
A    4 non-null int64
B    4 non-null object
C    4 non-null int64
D    4 non-null object
dtypes: int64(2), object(2)
memory usage: 200.0+ bytes
Run Code Online (Sandbox Code Playgroud)

让我们使用select_dtypes包括所有'object'类型转换和重新组合select_dtypes以排除它们.

df = pd.concat([
        df.select_dtypes([], ['object']),
        df.select_dtypes(['object']).apply(pd.Series.astype, dtype='category')
        ], axis=1).reindex_axis(df.columns, axis=1)

df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 4 columns):
A    4 non-null int64
B    4 non-null category
C    4 non-null int64
D    4 non-null category
dtypes: category(2), int64(2)
memory usage: 208.0 bytes
Run Code Online (Sandbox Code Playgroud)


小智 5

我认为这是一种更优雅的方式:

df = pd.DataFrame(dict(
        A=[1, 2, 3, 4],
        B=list('abcd'),
        C=[2, 3, 4, 5],
        D=list('defg')
    ))

df.info()

df.loc[:, df.dtypes == 'object'] =\
    df.select_dtypes(['object'])\
    .apply(lambda x: x.astype('category'))

df.info()
Run Code Online (Sandbox Code Playgroud)