2016-06-26 3 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 

[更新]、または各ラインを1つのファイルと一つの属性間のシングルマッチで別の表現で:

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 

どうすればPython(2.7.x)で実行できますか? (そしてパンダの有無にかかわらず、私はパンダが助けてくれると思う)

答えて

4

アップデート2:私はデータフレームとして出力[202]を設定するにはどうすればよい

はどのように私は、統計表

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を生成することができますか?

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

そして、私は各行に1つだけの属性を持つ元のDFを持っている、例えば。 'File_001 a1'(改行)' File_001 a2'(改行) 'File 002 a1'などコンパウンドコード行をどのように調整して望みの出力を達成するか(DFとしても)? –

+1

@JimRaynor、私は答えを更新しました - – MaxU

0

ファイルを読んでいる間;読み込んだ各属性について、キーに属性が含まれているかどうかを確認します。そうでない場合は、それを追加し、その属性を読み取ったファイル名をそのキーの値に追加し、属性がすでにマップのキーである場合は、ファイル名を値として追加します。

関連する問題