2017-10-26 14 views
1

私は次のような構造を持つデータフレーム持っている:私はにこれを変換したい並べ替える列

ID Material Description color size dim color size dim Tech 
1 xcv456 Rubber  101 s 32 102 m 34 elastic 

ID Material Description color size dim tech 
1 xcv456 Rubber  101 s 32 elastic 
1 xcv456 Rubber  102 m 34 elastic 

を、私は、このファイルを持っています5行と5414列で、私のプログラムが冗長列を検出し、必要な出力形式に変換するプロセスを自動化しようとしています。どんな助けでも大歓迎です。

答えて

2

用途:

#mask for all duplicates columns 
m = df.columns.duplicated(keep=False) 
#set index with not dupe columns 
df = df.set_index(df.columns[~m].tolist()) 
#count dupes for MultiIndex 
s = df.columns.to_series() 
df.columns = [df.columns, s.groupby(s).cumcount()] 
#reshape and remove 4 level, because 4 non dupe columns 
df = df.stack().reset_index(level=4, drop=True).reset_index() 
print (df) 
    ID Material Description  Tech color dim size 
0 1 xcv456  Rubber elastic 101 32 s 
1 1 xcv456  Rubber elastic 102 34 m 

print (df) 
    ID Material Description color size dim color size dim  Tech 
0 1 xcv456  Rubber 101 s 32 102 m 34 elastic 
1 2 xcv457  Rubber1 101 s 37 108 m 55 elastic2 

#mask for all duplicates columns 
m = df.columns.duplicated(keep=False) 
#set index with not dupe columns 
df = df.set_index(df.columns[~m].tolist()) 
#count dupes for MultiIndex 
s = df.columns.to_series() 
df.columns = [df.columns, s.groupby(s).cumcount()] 
df = df.stack().reset_index(level=4, drop=True).reset_index() 
print (df) 
    ID Material Description  Tech color dim size 
0 1 xcv456  Rubber elastic 101 32 s 
1 1 xcv456  Rubber elastic 102 34 m 
2 2 xcv457  Rubber1 elastic2 101 37 s 
3 2 xcv457  Rubber1 elastic2 108 55 m 
+1

@Bharathshettyを使用する前に、少しのプロセスが必要 - – jezrael

+0

がよろしいですありがとう!私はそれをテストし、素敵な作業 – jezrael

+1

私は答えを編集する、それはうまく動作します – jezrael

1

pd.wide_to_Long

hh=pd.Series(df.columns) 
df.columns=hh+hh.groupby(hh).cumcount().add(1).astype(str) 
pd.wide_to_long(df,['color','size','dim'],i=['ID1','Material1','Description1','Tech1'],j='drop').reset_index().drop('drop',1 
                               ) 
Out[556]: 
    ID1 Material1 Description1 Tech1 color size dim 
0 1 xcv456  Rubber elastic 101 s 32 
1 1 xcv456  Rubber elastic 102 m 34 
関連する問題