2016-10-24 60 views
3

我有一個Excel文件,其索引合併到Excel中的多行中,當我在熊貓中加載它時,它讀取第一行作爲索引標籤,其餘(合併細胞)充滿NaN。我怎樣才能循環索引,以便它填充與相應的索引NaNs?如何填寫熊貓指數NaN的

編輯:通過請求刪除excel的圖像。我沒有任何特定的代碼,但我可以寫一個例子。

import pandas as pd 
df = pd.read_excel('myexcelfile.xlsx', header=1) 
df.head() 
        Index-header    Month 
0       Index1     1 
1       NaN      2  
2       NaN      3  
3       NaN      4  
4       NaN      5 
5       Index2     1 
6       NaN      2 
... 
+1

請不要把圖片在這裏。閱讀[如何製作可重複使用的熊貓示例](http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples),並在此放置一些剪貼板友好的代碼。還分享你用來閱讀這段代碼。 – Ivan

回答

4

試試這個:

In [205]: df 
Out[205]: 
    Index-header Month 
0   Index1 1.0 
1   NaN 2.0 
2   NaN 3.0 
3   NaN 4.0 
4   NaN 5.0 
5   Index2 1.0 
6   NaN 2.0 
...   NaN NaN 

In [206]: df['Index-header'] = df['Index-header'].fillna(method='pad') 

In [207]: df 
Out[207]: 
    Index-header Month 
0   Index1 1.0 
1   Index1 2.0 
2   Index1 3.0 
3   Index1 4.0 
4   Index1 5.0 
5   Index2 1.0 
6   Index2 2.0 
...  Index2 NaN 
2
from StringIO import StringIO 
import pandas as pd 

txt = """Index1,1 
,2 
,3 
Index2,1 
,2 
,3""" 

df = pd.read_csv(StringIO(txt), header=None, index_col=0, names=['Month']) 
df 

enter image description here

df.set_index(df.index.to_series().ffill(), inplace=True) 
df 

enter image description here