使用apply
とpd.Series.astype
ためhttp://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.convert_objects.htmlと同様のものを探しています
編集
はpd.DataFrame
df
df = pd.DataFrame(dict(
A=[1, 2, 3, 4],
B=list('abcd'),
C=[2, 3, 4, 5],
D=list('defg')
))
df
を考えてみましょう
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
確かにこれは素晴らしいスタートです。しかし、私はあなたのソリューション "brute-forcely"がカテゴリ –
に何かを変換するので、オブジェクトdtypeを浮動小数点または整数に変換したくないだけです:df.select_dtypes(include = ['object'])。apply(pd.Series.astype、dtype = 'category')。info()は部分的に動作します。すべてのオブジェクトが変換されます。しかしその後、手動で数値列とのマージを実行する必要があります。これを防止し、dtypesを選択的に変更するにはどうすればいいですか? –
@GeorgHeiler私の投稿が更新されました – piRSquared