2016-06-26 2 views
1

100 개의 파일이 있다고 가정하고 모든 파일을 반복합니다. 각 파일에는 다음과 같은 여러 속성의 레코드가 있습니다. (모든 파일을 읽기 전에 속성의 총 개수를 알 수 없음)Python에서 피벗 데이터 생성

모든 파일을 읽은 후 20 개의 다른 속성과 다음 정보를 얻는 간단한 경우를 가정합니다. :

File_001: a1, a3, a5, a2 
File_002: a1, a3 
File_003: a4 
File_004: a4, a2, a6 
File_005: a7, a8, a9 
... 
File_100: a19, a20 

[업데이트] 또는 각 라인은 하나 개의 파일과 하나 개의 속성 사이에 단일 일치하는 또 다른 표현에 : 나는 "반대"통계 테이블, 즉 생성 할 수있는 방법

File_001: a1 
File_001: a3 
File_001: a5 
File_001: a2 
File_002: a1 
File_002: a3 
File_003: a4 
File_004: a4 
File_004: a2 
File_004: a6 
... 
File_100: a19 
File_100: a20 

가 :

a1: File_001, File_002, File_006, File_083 
a2: File_001, File_004 
... 
a20: File_099, File_100 

어떻게 파이썬 (2.7.x)에서 할 수 있습니까? (팬더가 있든 없든 나는 팬더가 도움이된다고 생각한다)

답변

4

UPDATE2 :방법 I는 "리버스"통계 테이블을 생성 할 수

In [9]: df 
Out[9]: 
     file attr 
0 File_001 a1 
1 File_001 a3 
2 File_001 a5 
3 File_001 a2 
4 File_002 a1 
5 File_002 a3 
6 File_003 a4 
7 File_004 a4 
8 File_004 a2 
9 File_004 a6 
10 File_100 a19 
11 File_100 a20 

In [10]: df.groupby('attr')['file'].apply(list) 
Out[10]: 
attr 
a1  [File_001, File_002] 
a19    [File_100] 
a2  [File_001, File_004] 
a20    [File_100] 
a3  [File_001, File_002] 
a4  [File_003, File_004] 
a5    [File_001] 
a6    [File_004] 
Name: file, dtype: object 

UPDATE : I가 DataFrame로서 출력한다 [202]을 설정하는 방법

?

new = (df.set_index('file') 
     .apply(lambda x: pd.Series(x['attr']), axis=1) 
     .stack() 
     .reset_index(level=1, drop=True) 
     .reset_index(name='attr') 
     .groupby('attr')['file'] 
     .apply(list) 
) 

그래서 나는 HTML 또는 CSV로 내보내기 할 수 있습니까?

new.to_csv('/path/to/file.csv', index=False) 

또는

html_text = new.to_html(index=False) 

원래 답 : 여기

는 팬더 솔루션입니다 :

원래 DF :

In [201]: df 
Out[201]: 
     file    attr 
0 File_001 [a1, a3, a5, a2] 
1 File_002   [a1, a3] 
2 File_003    [a4] 
3 File_004  [a4, a2, a6] 
4 File_005  [a7, a8, a9] 
5 File_100  [a19, a20] 

솔루션 :

In [202]: %paste 
(df.set_index('file') 
    .apply(lambda x: pd.Series(x['attr']), axis=1) 
    .stack() 
    .reset_index(level=1, drop=True) 
    .reset_index(name='attr') 
    .groupby('attr')['file'] 
    .apply(list) 
) 
## -- End pasted text -- 

출력 :

Out[202]: 
attr 
a1  [File_001, File_002] 
a19    [File_100] 
a2  [File_001, File_004] 
a20    [File_100] 
a3  [File_001, File_002] 
a4  [File_003, File_004] 
a5    [File_001] 
a6    [File_004] 
a7    [File_005] 
a8    [File_005] 
a9    [File_005] 
Name: file, dtype: object 
+0

감사합니다! 그것은 완벽하게 작동합니다! 출력 [202]을 DataFrame으로 어떻게 설정합니까? 그래서 html 또는 csv로 내보낼 수 있습니까? 결과는 내보낼 방법이없는 것 같습니다. –

+0

그리고 각 줄에 하나의 속성 만있는 원본 DF가있는 경우 (예 : 'File_001 a1' (개행)'File_001 a2' (개행)'File 002 a1' 등 욕망의 결과를 얻기 위해 복합 코드 라인을 조정하는 법 (DF처럼)? –

+1

@JimRaynor, 대답을 업데이트했습니다. – MaxU

0

파일을 읽는 중; 읽은 각 속성에 대해 키에 속성이 포함되어 있는지 확인하려면지도를 확인하십시오. 그렇지 않다면 추가하고, 그 속성을 읽은 파일 이름을 그 키 값에 추가하십시오. 속성이 이미지도의 키인 경우, 파일 이름을 값으로 추가하십시오.