2016-10-06 33 views
2
類別

我想有公頃優雅功能投所有對象列在大熊貓數據 幀類別熊貓投所有對象列於

df[x] = df[x].astype("category")執行類型投 df.select_dtypes(include=['object'])將子選擇所有類別的列。但是這會導致其他列丟失/需要手動合併。有沒有一種解決方案「就地運作」或不需要手動投射?

編輯

我要尋找類似http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.convert_objects.html東西轉換到分類數據

回答

3

使用applypd.Series.astypedtype='category'

考慮pd.DataFramedf

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

enter image description here

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 
+0

確實這是一個很好的開始。但我只想轉換對象dtype,而不是浮點或整數,因爲你的解決方案「蠻力」將任何東西轉換爲類別 –

+0

This:df.select_dtypes(include = ['object'])。apply(pd.Series.astype,dtype ='category')。info()部分工作,例如所有對象都被轉換。但之後需要手動執行與數字列的合併。我怎樣才能防止這種情況,並有選擇地改變地方的dtypes –

+0

@GeorgHeiler我的帖子已更新 – piRSquared