2017-02-13 10 views
2

저는 팬더 데이터 프레임 컬럼을 인수 분해했지만 원래의 컬럼 값을 덮어 썼습니다.팬더는 인수 분해 된 데이터 프레임에서 문자열 레이블을 가져옵니다.

원래 매핑 값을 다시 참조 할 수있는 방법이 있습니까?

예 :

enter image description here

df_test = pd.DataFrame({'col1': pd.Series(['cat','dog','cat','mouse'])}) 
df_test['col1'] = pd.factorize(df_test['col1'])[0] 
df_test 
그러나 나는 정수가지도 내용을 확인하려면 아래 다시 전화 할 수 있어야합니다. 데이터 프레임을 다시 초기화하지 않고 매핑을 검사 할 수있는 방법이 있습니까? -

pd.factorize(df_test)[1] 
나는 당신에게 약간 다른 접근 방법을 건의 할 것

답변

1

categorical dtype 사용

In [44]: df_test['col1'].cat.codes 
Out[44]: 
0 0 
1 1 
2 0 
3 2 
dtype: int8 

메모리 사용 400K DataFrame에 대한 :

In [74]: df_test = pd.DataFrame({'col1': pd.Series(['cat','dog','cat','mouse'])}) 

In [75]: df_test = pd.concat([df_test] * 10**5, ignore_index=True) 

In [76]: df_test.shape 
Out[76]: (400000, 1) 

In [77]: d1 = df_test.copy() 

In [78]: d2 = df_test.copy() 

In [79]: d1.col1 = pd.factorize(d1.col1)[0] 

In [80]: d2.col1 = d2.col1.astype('category') 

In [81]: df_test.info() 
<class 'pandas.core.frame.DataFrame'> 
RangeIndex: 400000 entries, 0 to 399999 
Data columns (total 1 columns): 
col1 400000 non-null object 
dtypes: object(1) 
memory usage: 3.1+ MB 

In [82]: d1.info() 
<class 'pandas.core.frame.DataFrame'> 
RangeIndex: 400000 entries, 0 to 399999 
Data columns (total 1 columns): 
col1 400000 non-null int64 
dtypes: int64(1) 
memory usage: 3.1 MB 

In [83]: d2.info() 
<class 'pandas.core.frame.DataFrame'> 
RangeIndex: 400000 entries, 0 to 399999 
Data columns (total 1 columns): 
col1 400000 non-null category 
dtypes: category(1) 
memory usage: 390.7 KB   # categorical column takes almost 8x times less memory 

In [40]: df_test['col1'] = df_test['col1'].astype('category') 

In [41]: df_test 
Out[41]: 
    col1 
0 cat 
1 dog 
2 cat 
3 mouse 

In [42]: df_test.dtypes 
Out[42]: 
col1 category 
dtype: object 

을 당신은 숫자를 필요로하는 경우

+0

내가하고있는 일은 무엇입니까? 원본과 카테고리 코드 :'df_test [ 'col1'] = df_test [ 'col1'] .cat.codes'. 그래서 고양이 코드를 카테고리에 다시 매핑 할 수있게하려면 하나는 모두 cat.codes이고 다른 하나는 매핑 카테고리가있는 2 개의 데이터 프레임을 만들어야합니까? 아니면 더 좋은 방법이 있습니까? – jxn