2016-06-28 28 views
0

我有一個熊貓數據幀是這樣的:熊貓數據框中加入行並設置列名

 1  2  3 
0 
NaN ingr contr count 
2.0 water 0.02 275 
3.0 oil 0.23 11 
..... 

,我想將它轉移到這一點:

ingr contr count 
water 0.02 275 
oil 0.23 11 
.... 

我試圖用pd.droppd.set_index()等等,但我無法弄清楚如何做到這一點。任何人都可以幫助我?

回答

1

嘗試iloc索引:

In [66]: df 
Out[66]: 
      1  2  3 
NaN ingr contr count 
2.0 water 0.02 275 
3.0 oil 0.23  11 

In [67]: df.columns = df.iloc[0] 

In [68]: df = df.iloc[1:].reset_index() 

In [69]: df 
Out[69]: 
nan index ingr contr count 
0  2.0 water 0.02 275 
1  3.0 oil 0.23 11 

PS,但它會更有效地讀取數據正確地從使用的read_csv()/read_excel/read_table /等headerskiprows等參數十分開始。 C函數

+0

謝謝你MaxU幫了我很多與此! – Papie

+0

df.iloc如何工作?因爲你挑選了iloc [0],這是指列名? – Papie

+0

@Papie,你如何閱讀你的數據?我認爲它應該在閱讀過程中修復/更正 – MaxU

1

使用ilocreset_indexrename_axis(新中pandas0.18.0):

df.columns = df.iloc[0,:] 
print (df.iloc[1:,:].reset_index().rename_axis(None, axis=1)) 
    0 ingr contr count 
0 2.0 water 0.02 275 
1 3.0 oil 0.23 11 

如果不需要舊索引添加參數drop=True

df.columns = df.iloc[0,:] 
print (df.iloc[1:,:].reset_index(drop=True).rename_axis(None, axis=1)) 
    ingr contr count 
0 water 0.02 275 
1 oil 0.23 11 

如果你需要先列索引的使用set_index

df.columns = df.iloc[0,:] 
print (df.iloc[1:,:].set_index('ingr').rename_axis(None, axis=1).rename_axis(None)) 
     contr count 
water 0.02 275 
oil 0.23 11