2017-06-01 32 views
2

我有一個DF有很多列:重新整理數據框尺寸

date risk lev chemical weight date risk lev chemical weight 
15-5-16 5   Potasium 5mg 15-5-16  3  Sodium  7 mg 
14-5-16 6   Potasium 10mg 14-5-16  2  Sodium  2 mg 

我想重新安排一下,使每個4列闖入新行,如DF是這樣的:

date risk lev chemical weight 
15-5-16  5  Potasium 5mg 
15-5-16  3  Sodium 7mg 
14-5-16  6  Potasium 10mg 
14-5-16  2  Sodium 2mg 

對不起,我不包括我的嘗試,但還是第一次我解決這個問題,不知道如何着手

+0

你有重複的列名嗎? – jezrael

+0

是的,它們是重複的。 – ge00rge

回答

2

先刪除重複列名,然後使用pd.lreshapedict comprehension創建dict

s = df.columns.to_series() 
df.columns = s.add(s.groupby(s).cumcount().astype(str)) 
print (df) 
    date0 risk lev0 chemical0 weight0 date1 risk lev1 chemical1 weight1 
0 15-5-16   5 Potasium  5mg 15-5-16   3 Sodium  7mg 
1 14-5-16   6 Potasium 10mg 14-5-16   2 Sodium  2mg 


cols = ['date','risk lev','chemical','weight'] 
d = {x:df.columns[df.columns.str.startswith(x)].tolist() for x in cols} 
print (d) 
{'date': ['date0', 'date1'], 
'weight': ['weight0', 'weight1'], 
'risk lev': ['risk lev0', 'risk lev1'], 
'chemical': ['chemical0', 'chemical1']} 

df = pd.lreshape(df, d) 
print (df) 
     date weight risk lev chemical 
0 15-5-16 5mg   5 Potasium 
1 14-5-16 10mg   6 Potasium 
2 15-5-16 7mg   3 Sodium 
3 14-5-16 2mg   2 Sodium 
2

第一列名擺脫重複的:

In [248]: df 
Out[248]: 
     date risk lev chemical weight date.1 risk lev.1 chemical.1 weight.1 
0 15-5-16   5 Potasium 5mg 15-5-16   3  Sodium  7 mg 
1 14-5-16   6 Potasium 10mg 14-5-16   2  Sodium  2 mg 

現在我們可以使用pd.lreshape

In [249]: d = { 
    ...:  'chemical': ['chemical','chemical.1'], 
    ...:  'weight':['weight','weight.1'], 
    ...:  'date':['date','date.1'], 
    ...:  'risk lev': ['risk lev','risk lev.1'] 
    ...: } 

In [250]: pd.lreshape(df, d) 
Out[250]: 
    chemical weight  date risk lev 
0 Potasium 5mg 15-5-16   5 
1 Potasium 10mg 14-5-16   6 
2 Sodium 7 mg 15-5-16   3 
3 Sodium 2 mg 14-5-16   2 
0

這個問題更穩健與pd.wide_to_long解決。您必須先在每列的末尾放置一個數字。

df.columns = [col + str(i//4 + 1) for i, col in enumerate(df.columns)] 

pd.wide_to_long(df.reset_index(), 
       stubnames=['date', 'risk lev', 'chemical', 'weight'], 
       i='index', 
       j='dropme').reset_index(drop=True) 

     date risk lev chemical weight 
0 15-5-16   5 Potasium 5mg 
1 14-5-16   6 Potasium 10mg 
2 15-5-16   3 Sodium 7mg 
3 14-5-16   2 Sodium 2mg 
+0

現在我正在度假,所以不能用替代解決方案編輯lreshape答案。非常抱歉。 – jezrael