使用apply
和pd.Series.astype
,并指定dtype='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
![输入图片描述](https://istack.dev59.com/qcECx.webp)
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
使用 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